"use client";
import Loading from "@/views/profile/loading";
import { useUserData } from '@/store/user-profile';
import Image from "@/ui/image";
import { ClipboardMinus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { useNavigate } from "react-router-dom";
import { useUserSelection } from "@/store/user-payment";

const PaymentList = () => {
    const { profile, loading, error } = useUserData();
    const { t } = useTranslation();
    const navigate = useNavigate();
    const context = useUserSelection();

    if (!context) {
        console.error('Payment context is not available');
        return <p>Payment system is not available. Please try again later.</p>;
    }

    const { setSelectedPayment, setRowDetails } = context;

    const handlePaymentClick = (paymentType: 'bank-transfer' | 'fatoorah', row: any, installment: any) => {
        if (row?.status === 'paid') return;

        const parent = installment;
        const courseId = parent?.course?.id || parent?.course_id;

        if (!courseId) {
            console.error('Course ID is missing');
            return;
        }

        const paymentTitle = paymentType === 'bank-transfer'
            ? t('training-courses.bank-transfer.title')
            : t('training-courses.fatoorah.title');

        // Calculate current installment number based on the row index
        const currentInstallmentNumber = parent?.installment_schedule?.findIndex((schedule: any) => schedule.id === row?.id) + 1;

        // Update the context with payment details including installment data
        setSelectedPayment({
            ...context.selectedPayment,
            payment: paymentType,
            paymentInAr: paymentTitle,
            dueDate: row?.due_date || '',
            monthlyPayment: row?.monthly_payment || '',
            installmentCount: parent?.installment_count || '',
            currentInstallmentNumber: currentInstallmentNumber
        });

        // Use course.id from the response object for course_registrations_id
        const registrationId = parent?.course?.id || parent?.course_registration_id || parent?.course_registrations_id || '';

        setRowDetails({
            ...context.rowDetails,
            courseId: String(courseId),
            thisRowPrice: String(row?.monthly_payment || ''),
            totalPrice: String(parent?.course_price || ''),
            courseRegistrationId: registrationId,
            installmentId: String(parent?.id || ''),
            installmentScheduleId: row?.id || ''
        });

        // Navigate to payment page with state, including auto-trigger flag for fatoorah
        navigate(`/training-courses/${courseId}/payment/card`, {
            state: {
                fromProfile: true,
                courseId: String(courseId),
                price: String(row?.monthly_payment || ''),
                totalPrice: String(parent?.course_price || ''),
                courseRegistrationId: registrationId,
                course_registrations_id: registrationId,
                payment: paymentType,
                paymentTitle: paymentTitle,
                dueDate: row?.due_date || '',
                monthlyPayment: row?.monthly_payment || '',
                installmentId: String(parent?.id || ''),
                installmentScheduleId: row?.id || '',
                installmentCount: parent?.installment_count || '',
                currentInstallmentNumber: currentInstallmentNumber,
                autoTriggerPayment: paymentType === 'fatoorah', // Auto-trigger for fatoorah
                rowDetails: {
                    courseId: String(courseId),
                    thisRowPrice: String(row?.monthly_payment || ''),
                    totalPrice: String(parent?.course_price || ''),
                    courseRegistrationId: registrationId,
                    installmentId: String(parent?.id || ''),
                    installmentScheduleId: row?.id || ''
                }
            }
        });
    };

    // Helper function to check if payment is allowed based on due date
    const isPaymentAllowed = (dueDate: string) => {
        if (!dueDate) return true; // If no due date, allow payment

        const today = new Date();
        const due = new Date(dueDate);
        const twoDaysBeforeDue = new Date(due);
        twoDaysBeforeDue.setDate(due.getDate() - 2);

        // Allow payment if today is 2 days before due date or later
        return today >= twoDaysBeforeDue;
    };

    if (loading) {
        return (
            <>
                <Loading />
            </>
        )
    };

    if (error) {
        return (
            <p>{error?.message}</p>
        )
    };

    if (profile?.payment?.length === 0) {
        return (
            <div className="grid h-full w-full place-items-center max-lg:p-8">
                <p className="text-center text-gray-600 text-lg flex items-center gap-2">
                    {t("profile.no-payment")} <ClipboardMinus />
                </p>
            </div>
        )
    };

    const hasInstallments = Array.isArray(profile?.Installments) && profile?.Installments.length > 0;

    return (
        <div>
            {hasInstallments && (
                <div className="space-y-4">

                    {profile?.Installments?.map((installment: any, installmentIndex: number) => (
                        <section key={installment?.id || installmentIndex} className="border rounded-lg relative p-3 mb-10 bg-white mt-12">
                            <p className="bg-primary-tw text-white px-3 py-1 rounded-md w-max mb-4 absolute right-[48%] top-[-15px] translate-x-[50%]">
                                {t('profile.installments') || 'Installments'}
                            </p>
                            <div className="mb-4">
                                <h3 className="font-semibold text-lg text-primary-tw mb-2">
                                    {installment?.course?.title || `Course ${installmentIndex + 1}`}
                                </h3>
                                <div className="text-sm space-y-3">
                                    <p className="flex justify-start">
                                        <strong className='text-gray-500'>{t('profile.total-monay') || 'Total'}:</strong>
                                        <span className="text-primary-tw px-4 rounded-md font-bold">{installment?.course_price}</span>
                                    </p>
                                    <p className="flex justify-start">
                                        <strong className='text-gray-500'>{t('profile.paid-monay') || 'Paid'}:</strong>
                                        <span className="text-primary-tw px-4 rounded-md font-bold">{installment?.amount_paid}</span>
                                    </p>
                                    <p className="flex justify-start">
                                        <strong className="text-gray-500">{t('profile.count-installments') || 'Installments'}:</strong>
                                        <span className="text-primary-tw px-4 rounded-md font-bold">{installment?.installment_count}</span>
                                    </p>
                                </div>
                            </div>

                            {Array.isArray(installment?.installment_schedule) && installment?.installment_schedule?.length > 0 && (
                                <div className="mt-3">
                                    <p className="font-semibold mb-2">{t('profile.installment_schedule') || 'Installment Schedule'}</p>
                                    
                                    {/* Desktop Table View */}
                                    <div className="hidden md:block w-full overflow-x-auto">
                                        <table className="w-full text-sm border rounded-md">
                                            <thead className="bg-gray-100">
                                                <tr>
                                                    <th className="text-center p-2">#</th>
                                                    <th className="text-center p-2">{t('profile.due_date') || 'Due date'}</th>
                                                    <th className="text-center p-2">{t('profile.monthly_payment') || 'Monthly payment'}</th>
                                                    <th className="text-center p-2">{t('profile.status') || 'Status'}</th>
                                                    <th className="text-center p-2">{t('profile.actions') || 'Actions'}</th>
                                                </tr>
                                            </thead>
                                            <tbody className="text-center">
                                                {installment?.installment_schedule?.map((row: any, idx: number) => (
                                                    <tr key={row?.id || idx} className="border-t">
                                                        <td className="p-2">{idx + 1}</td>
                                                        <td className="p-2">{row?.due_date}</td>
                                                        <td className="p-2">{row?.monthly_payment}</td>
                                                        <td className="p-2">
                                                            <span className={`px-2 py-0.5 rounded text-xs ${row?.status === 'paid' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-800'}`}>
                                                                {row?.status === 'paid' ? t('paid') : t('pending')}
                                                            </span>
                                                        </td>
                                                        <td className="p-2">
                                                            <div className="flex items-center justify-center gap-2 flex-col lg:flex-row sm:gap-3">
                                                                <Button
                                                                    variant="outline"
                                                                    size="sm"
                                                                    className="bg-secondary-tw text-white hover:opacity-90 text-xs"
                                                                    disabled={row?.status === 'paid' || !isPaymentAllowed(row?.due_date)}
                                                                    onClick={() => handlePaymentClick('bank-transfer', row, installment)}
                                                                >
                                                                    {t('training-courses.bank-transfer-title')}
                                                                </Button>
                                                                <Button
                                                                    size="sm"
                                                                    className="bg-primary-tw text-white hover:opacity-90 text-xs"
                                                                    disabled={row?.status === 'paid' || !isPaymentAllowed(row?.due_date)}
                                                                    onClick={() => handlePaymentClick('fatoorah', row, installment)}
                                                                >
                                                                    {t('training-courses.fatoorah-title')}
                                                                </Button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>

                                    {/* Mobile Card View */}
                                    <div className="md:hidden space-y-3">
                                        {installment?.installment_schedule?.map((row: any, idx: number) => (
                                            <div key={row?.id || idx} className="bg-white border rounded-lg p-4 shadow-sm">
                                                <div className="flex justify-between items-start mb-3">
                                                    <div className="bg-primary-tw text-white px-2 py-1 rounded text-xs font-medium">
                                                        #{idx + 1}
                                                    </div>
                                                    <span className={`px-2 py-1 rounded text-xs font-medium ${row?.status === 'paid' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-800'}`}>
                                                        {row?.status === 'paid' ? t('paid') : t('pending')}
                                                    </span>
                                                </div>
                                                <div className="space-y-2 mb-4">
                                                    <div className="flex justify-between">
                                                        <span className="text-gray-600 text-sm">{t('profile.due_date') || 'Due date'}:</span>
                                                        <span className="font-medium text-sm">{row?.due_date}</span>
                                                    </div>
                                                    <div className="flex justify-between">
                                                        <span className="text-gray-600 text-sm">{t('profile.monthly_payment') || 'Monthly payment'}:</span>
                                                        <span className="font-medium text-sm text-primary-tw">{row?.monthly_payment}</span>
                                                    </div>
                                                </div>
                                                <div className="flex flex-col gap-2">
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        className="bg-secondary-tw text-white hover:opacity-90 w-full"
                                                        disabled={row?.status === 'paid' || !isPaymentAllowed(row?.due_date)}
                                                        onClick={() => handlePaymentClick('bank-transfer', row, installment)}
                                                    >
                                                        {t('training-courses.bank-transfer-title')}
                                                    </Button>
                                                    <Button
                                                        size="sm"
                                                        className="bg-primary-tw text-white hover:opacity-90 w-full"
                                                        disabled={row?.status === 'paid' || !isPaymentAllowed(row?.due_date)}
                                                        onClick={() => handlePaymentClick('fatoorah', row, installment)}
                                                    >
                                                        {t('training-courses.fatoorah-title')}
                                                    </Button>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </section>
                    ))}
                </div>
            )}

            <ul>
                {profile?.payment.map((item, index: number) => (
                    <li key={index} className="bg-light-gray !p-4 mb-2 flex items-start gap-4 max-lg:flex-col">
                        {item.image && (
                            <div className="relative w-52 h-20 max-lg:w-full">
                                <Image src={item.image} alt="invoice" className="w-52 h-20 rounded-md object-cover max-lg:w-full" />
                            </div>
                        )}
                        <div className="flex items-center justify-between w-full flex-wrap">
                            <div className="text-start space-y-2">
                                <p className="text-sm capitalize">{t('profile.payment-type')}</p>
                                <strong className="capitalize text-primary-tw">
                                    {item?.payment_type?.replaceAll('_', ' ')}
                                </strong>
                            </div>

                            <div className="text-start space-y-2">
                                <p className="text-sm">{t('profile.payment-date')}</p>
                                <strong className="capitalize text-primary-tw">{item?.created_at}</strong>
                            </div>

                            <div className="text-start space-y-2">
                                <p className="text-sm">{t('profile.price')}</p>
                                <strong className="capitalize text-primary-tw">{item?.price}</strong>
                            </div>

                            <div className="text-start space-y-2">
                                <p className="text-sm">{t('profile.status')}</p>
                                <strong className="capitalize text-primary-tw">
                                    {item.payment_status === "pending"
                                        ? t('profile.pending')
                                        : item.payment_status === "installment"
                                            ? t('profile.installment')
                                            : t('profile.not-pending')}
                                </strong>
                            </div>
                        </div>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default PaymentList;