"use client";
import { useToken } from "@/hooks/use-token";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation } from "@tanstack/react-query";
import { toast } from "@/hooks/use-toast";

import { Bomb, Loader, SaudiRiyal, TriangleAlert } from "lucide-react";

import { useLanguage } from "@/store/language-context";
import { useUserSelection } from "@/store/user-payment";

import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { RowDetails, SelectedPayment } from "@/types";

export default function TRCourseTable({ table, error, isLoading }) {
    const { URL } = useLanguage();
    const { t } = useTranslation();

    const { id } = useParams();
    const navigate = useNavigate();

    const token = useToken();
    const { setSelectedPayment, setRowDetails, rowDetails } = useUserSelection();

    const [rowIndex, setRowIndex] = useState(null);

    const courseMutation = useMutation({
        mutationKey: ['table-row'],
        mutationFn: async (variables: { rowId: number; price: number }) => {
            const { rowId, price } = variables;
            setRowIndex(rowId);

            if (!token) {
                navigate('/login');
                return;
            }
            const response = await axios.post(`${URL}/course-register`, {
                course_id: rowDetails?.courseId || id,
                city_month_data_id: rowId,
                price: price,
            }, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json"
                }
            });

            return response
        },
        onError: (error: Error | any) => {
            const msg = error?.response?.data.message;
            if (msg?.includes('already')) {
                toast({
                    variant: "destructive",
                    title: (
                        <div className="flex items-center gap-2">
                            <TriangleAlert size={20} />
                            <span>
                                {t('training-courses.registered-before')}
                            </span>
                        </div>
                    )
                });
            } else if (msg?.includes("Unauthenticated")) {
                toast({
                    variant: "destructive",
                    title: (
                        <div className="flex items-center gap-2">
                            <Bomb size={20} />
                            <span>
                                {t('custom.login-first')}
                            </span>
                        </div>
                    ),
                });
                setTimeout(() => navigate('/login'), 1500);
            } else {
                toast({
                    variant: "destructive",
                    title: (
                        <div className="flex items-center gap-2">
                            <Bomb size={20} />
                            <span>
                                {t('custom.err')}
                            </span>
                        </div>
                    )
                });
            }
        },
        onSuccess: (response) => {
            const dataOfRow = response?.data?.data;
            setRowDetails(prev => ({
                ...prev,
                courseId: id,
                thisUserId: dataOfRow?.user_id,
                thisCompanyId: dataOfRow?.company_id,
                courseRegistrationId: dataOfRow?.id,
                userToken: token,
                theImgUploaded: '',
                totalPrice: dataOfRow?.total,
                thisRowPrice: dataOfRow?.price,
                vat: dataOfRow?.total_vat,
                taxPercentage: dataOfRow?.tax?.percentage,

            }));

            navigate(`/training-courses/${id}/payment/way`);
        }
    });

    if (error) {
        <div className="grid place-items-center p-5">
            <p>{error?.message}</p>
        </div>
    };

    if (isLoading) {
        <div className="flex justify-between w-full">
            <div className="w-24 h-5 rounded-md l-load-dt m-2"></div>
            <div className="w-24 h-5 rounded-md l-load-dt m-2"></div>
            <div className="w-24 h-5 rounded-md l-load-dt m-2"></div>
            <div className="w-24 h-5 rounded-md l-load-dt m-2"></div>
            <div className="w-24 h-8 rounded-md l-load-dt m-2"></div>
        </div>
    };

    const register = (data: any, diffInDays: number) => {
        if (!token) {
            navigate('/login');
            return;
        };

        const updatedPayment: SelectedPayment = {
            location: data?.city?.title,
            currencyTitle: data?.currency?.title?.includes('ريال') ?
                <SaudiRiyal size={16} /> :
                data?.currency?.title,
            startDate: data?.start_date,
            endDate: data?.end_date,
            duration: diffInDays.toString(),
        };

        setSelectedPayment((prev: SelectedPayment) => ({
            ...prev,
            ...updatedPayment,
        }));

        courseMutation.mutate({ rowId: data?.id, price: data?.price });
    };

    return table?.length > 0 && (
        <div className="w-full lg:bg-[#FAFAFA] rounded-lg p-4 overflow-hidden">
            {/* Desktop Table View */}
            <div className="hidden lg:block">
                <Table className="w-full text-base">
                    <TableHeader className="bg-gray-50 sticky top-0 h-fit">
                        <TableRow className="border-b border-gray-100 hover:bg-[#FAFAFA] text-nowrap">
                            <TableHead className="text-primary-tw font-semibold w-[180px] text-start">
                                {t('contact.start-date')}
                            </TableHead>
                            <TableHead className="text-primary-tw font-semibold text-start">
                                {t('contact.end-date')}
                            </TableHead>
                            <TableHead className="text-primary-tw font-semibold text-start">
                                {t('training-courses.duration')}
                            </TableHead>
                            <TableHead className="text-primary-tw font-semibold text-start">
                                {t('training-courses.total-price')}
                            </TableHead>
                            <TableHead className="text-primary-tw font-semibold text-start">
                                {t('training-courses.actions')}
                            </TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {table?.map((data: any, i: number) => {
                            const startDate = new Date(data?.start_date);
                            const endDate = new Date(data?.end_date);
                            const diffMilliSec = Number(endDate) - Number(startDate);
                            const diffInDays = diffMilliSec / (1000 * 60 * 60 * 24) + 1;

                            return (
                                <TableRow key={i} className="border-b border-[#D9D9D9]">
                                    <TableCell className="py-3 text-nowrap">
                                        {data?.start_date || "_____"}
                                    </TableCell>
                                    <TableCell className="py-3 text-nowrap">
                                        {data?.end_date || "_____"}
                                    </TableCell>
                                    <TableCell className="py-3 text-nowrap">
                                        {diffInDays || "_____"}
                                        {!isNaN(diffInDays) && (diffInDays === 1 ? t('training-courses.day') : t('training-courses.days'))}
                                    </TableCell>
                                    <TableCell className="py-3">
                                        <div className="flex items-center gap-1 text-nowrap">
                                            {data?.price || "_____"} {" "}
                                            {(data?.currency?.title?.includes('ريال') || data?.currency?.title?.includes('Saudi')) ?
                                                <SaudiRiyal size={16} /> :
                                                data?.currency?.title || "_____"
                                            }
                                        </div>
                                    </TableCell>
                                    <TableCell className="py-3">
                                        <button
                                            onClick={() => register(data, diffInDays)}
                                            className="w-24 py-1 text-white flex justify-center items-center rounded-md bg-primary-tw cursor-pointer hover:bg-primary-tw/90 transition-colors"
                                            disabled={rowIndex === data?.id && courseMutation.isPending}
                                        >
                                            {(rowIndex === data?.id && courseMutation.isPending) ? (
                                                <Loader className="animate-spin" />
                                            ) : (
                                                t('custom.check')
                                            )}
                                        </button>
                                    </TableCell>
                                </TableRow>
                            );
                        })}
                    </TableBody>
                </Table>
            </div>

            {/* Mobile Card View */}
            <div className="lg:hidden space-y-4">
                {table?.map((data: any, i: number) => {
                    const startDate = new Date(data?.start_date);
                    const endDate = new Date(data?.end_date);
                    const diffMilliSec = Number(endDate) - Number(startDate);
                    const diffInDays = diffMilliSec / (1000 * 60 * 60 * 24) + 1;

                    return (
                        <div key={i} className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm">
                            <div className="space-y-3 mb-4">
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-600 text-sm font-medium">{t('contact.start-date')}:</span>
                                    <span className="font-semibold text-primary-tw">{data?.start_date || "_____"}</span>
                                </div>
                                
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-600 text-sm font-medium">{t('contact.end-date')}:</span>
                                    <span className="font-semibold text-primary-tw">{data?.end_date || "_____"}</span>
                                </div>
                                
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-600 text-sm font-medium">{t('training-courses.duration')}:</span>
                                    <span className="font-semibold">
                                        {diffInDays || "_____"}
                                        {!isNaN(diffInDays) && (diffInDays === 1 ? ` ${t('training-courses.day')}` : ` ${t('training-courses.days')}`)}
                                    </span>
                                </div>
                                
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-600 text-sm font-medium">{t('training-courses.total-price')}:</span>
                                    <div className="flex items-center gap-1 font-semibold text-primary-tw">
                                        {data?.price || "_____"} {" "}
                                        {(data?.currency?.title?.includes('ريال') || data?.currency?.title?.includes('Saudi')) ?
                                            <SaudiRiyal size={16} /> :
                                            data?.currency?.title || "_____"
                                        }
                                    </div>
                                </div>
                            </div>
                            
                            <button
                                onClick={() => register(data, diffInDays)}
                                className="w-full py-2 text-white flex justify-center items-center rounded-md bg-primary-tw cursor-pointer hover:bg-primary-tw/90 transition-colors font-medium"
                                disabled={rowIndex === data?.id && courseMutation.isPending}
                            >
                                {(rowIndex === data?.id && courseMutation.isPending) ? (
                                    <Loader className="animate-spin" />
                                ) : (
                                    t('custom.check')
                                )}
                            </button>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};