"use client";
import { courseHref } from "@/lib/course-url";
import { useToken } from "@/hooks/use-token";
import axios from "axios";
import { useEffect, useState } from "react";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";

import { Check, Clipboard, Loader, Paperclip, RefreshCcw, SaudiRiyal, X } from "lucide-react";

import { toast } from "@/hooks/use-toast";

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

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";

import IvoryLogo from "@/assets/icons/IvoryLogo.svg";
import PaymentCourseBox from "./payment-course-box";
import { RowDetails, SelectedPayment } from "@/types";

const PaymentCard = ({ page }: { page: "offers" | "training-courses" }) => {
    const { URL } = useLanguage();
    const { t } = useTranslation();

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

    if (typeof document !== "undefined") document.title = page === 'offers' ? `${t('routes.offers')} | ${t('routes.payment-card')}` : `${t('routes.training-courses')} | ${t('routes.payment-card')}`;

    const { id } = useParams();
    const location = useLocation() as any;

    const { data: course } = useQuery({
        queryKey: ['payment-data', id, page, URL],
        queryFn: async () => {
            const response = await axios.get(`${URL}/courses/${id}`);
            if (response.status !== 200) throw new Error(t('custom.err'));
            return response?.data?.data?.data ?? response?.data?.data;
        }
    });

    const navigate = useNavigate();
    const token = useToken();

    const IBAN = "SA7605000068205160261000";
    const [copyIcon, setCopyIcon] = useState(<Clipboard />);

    const [data, setData] = useState({
        couponCode: '',
        couponErr: null,
        discount: 0,
        discountPercentage: 0,
        imgUploaded: null,
        imgErr: null,
        cardLoading: false
    });

    const getPaymentLink = () => {
        if (page === "offers") {
            return `${URL}/offer/payment/${selectedPayment.payment}`;
        }

        if (selectedPayment.payment === "tabby" && !rowDetails.courseFeeId) {
            return `${URL}/tabby`;
        }

        if (rowDetails.courseFeeId) {
            return `${URL}/course/extra-fees/payment/${selectedPayment.payment}`;
        }

        // Check if this is an installment payment
        if (rowDetails.installmentId && rowDetails.installmentScheduleId) {
            if (selectedPayment.payment === 'bank-transfer') {
                return `${URL}/installment/payment-installment`;
            } else if (selectedPayment.payment === 'fatoorah') {
                return `${URL}/installment/payment/fatoorah`;
            }
        }

        return `${URL}/payment/${selectedPayment.payment}`;
    };

    const getRequestedBody = () => {
        if (page === "offers") {
            return {
                price: rowDetails?.courseOfferPrice,
                course_id: rowDetails?.courseId,
                course_offer_id: rowDetails?.courseOfferId
            };
        } else {
            if (rowDetails.courseFeeId && !rowDetails.courseRegistrationId) {
                return {
                    price: rowDetails.courseFeePrice,
                    course_fee_id: rowDetails.courseFeeId,
                    course_id: rowDetails?.courseId,
                };
            } else if (rowDetails.installmentId && rowDetails.installmentScheduleId) {
                // Installment payment body
                return {
                    installment_id: rowDetails.installmentId,
                    installment_schedule_id: rowDetails.installmentScheduleId,
                    course_id: rowDetails?.courseId,
                    price: rowDetails?.thisRowPrice
                };
            } else {
                return {
                    price: rowDetails?.thisRowPrice,
                    course_registrations_id: rowDetails?.courseRegistrationId,

                    total: rowDetails.totalPrice,
                    total_vat: rowDetails.vat,

                    coupon_code: data?.couponCode
                };
            }
        }
    };

    // coupon
    const couponMutation = useMutation({
        mutationFn: async () => {
            try {
                const response = await axios.get(`${URL}/check-coupon?coupon_code=${data.couponCode}&course_register_id=${rowDetails?.courseRegistrationId}`, {
                    headers: {
                        Authorization: `Bearer ${token}`
                    }
                });
                return response.data;
            } catch (error) {
                throw {
                    message: error.response?.data?.message || t('training-courses.coupon-notvalid'),
                    status: error.response?.status
                };
            }
        },
        onSuccess: (data) => {
            const incomeData = data?.data;

            if (incomeData?.coupon?.type === "fixed") {
                setData(prev => ({
                    ...prev,
                    discountPercentage: incomeData?.coupon?.percentage || 0,
                    discount: Number(incomeData?.coupon?.max_discount),
                    couponErr: null
                }));
            } else {
                setData(prev => ({
                    ...prev,
                    discountPercentage: incomeData?.coupon?.percentage || 0,
                    couponErr: null
                }));
            }
            setRowDetails((prev: RowDetails) => ({
                ...prev,
                vat: Number(incomeData?.calculated_data?.total_vat),
                thisRowPrice: Number(incomeData?.calculated_data?.price),
                totalPrice: Number(incomeData?.calculated_data?.total),
                priceBeforeDiscount: Number(incomeData?.course_register?.total)
            }));
        },
        onError: (error) => {
            setData(prev => ({
                ...prev,
                couponErr: error.message || t('training-courses.coupon-notvalid'),
                discountPercentage: 0
            }));
        }
    });

    // bank transfer (لو بنك)
    const bankTransferMutation = useMutation({
        mutationFn: async (formData: FormData) => {
            try {
                let endpoint;

                if (rowDetails.courseFeeId) {
                    endpoint = `${URL}/course/extra-fees/payment/bank-transfer`;
                } else if (rowDetails.installmentId && rowDetails.installmentScheduleId) {
                    endpoint = `${URL}/installment/payment-installment`;
                } else {
                    endpoint = `${URL}/payment/bank-transfer`;
                }

                const response = await axios.post(
                    endpoint,
                    formData,
                    {
                        headers: {
                            Authorization: `Bearer ${token}`,
                            "Content-Type": "multipart/form-data"
                        }
                    }
                );
                return response.data;
            } catch (error) {
                throw {
                    message: error.response?.data?.message || t('training-courses.img-err'),
                    status: error.response?.status,
                    data: error.response?.data
                };
            }

        },
        onSuccess: () => {
            toast({
                title: t('payment.done'),
                description: t('payment.we-will-see')
            });
        },
        onError: (error) => {
            setData(prev => ({
                ...prev,
                imgErr: error.message || t('training-courses.img-err')
            }));
        }
    });

    // payment (مش بنك)
    const paymentMutation = useMutation({
        mutationFn: async (paymentData: any) => {
            try {
                const response = await axios.post(
                    getPaymentLink(),
                    paymentData,
                    {
                        headers: {
                            Authorization: `Bearer ${token}`,
                            "Content-Type": "application/json"
                        }
                    }
                );
                return response.data;
            } catch (error) {
                throw {
                    message: error.response?.data?.message || t('training-courses.pay-err'),
                    status: error.response?.status,
                    data: error.response?.data
                };
            }
        },
        onSuccess: () => {
            toast({
                title: t('payment.done'),
            });
        },
        onError: () => {
            return;
        }
    });

    const isLoading = bankTransferMutation.isPending || paymentMutation.isPending || couponMutation.isPending;
    const error = bankTransferMutation.error || paymentMutation.error || couponMutation.error || data.couponErr;
    const resFromBank = bankTransferMutation.data || paymentMutation.data;

    const payFunc = async (e) => {
        e.preventDefault();
        setData(prev => ({ ...prev, cardLoading: true }));

        try {
            if (selectedPayment.payment === 'bank-transfer') {
                if (!data.imgUploaded) {
                    setData(prev => ({ ...prev, imgErr: t('training-courses.img-err'), cardLoading: false }));
                    return;
                }

                const formData = new FormData();
                formData.append('image', data.imgUploaded);
                formData.append("course_id", String(rowDetails.courseId));

                if (page === "offers") {
                    formData.append('price', rowDetails.courseOfferPrice);
                    formData.append('course_offer_id', rowDetails.courseOfferId);
                } else if (rowDetails.installmentId && rowDetails.installmentScheduleId) {
                    // Installment payment - use new endpoint parameters
                    formData.append('installment_id', String(rowDetails.installmentId));
                    formData.append('installment_schedule_id', String(rowDetails.installmentScheduleId));
                    formData.append('price', rowDetails.thisRowPrice);
                } else {
                    formData.append('price', rowDetails.thisRowPrice);
                    formData.append('total', rowDetails.totalPrice.toString());
                    formData.append('total_vat', rowDetails.vat.toString());
                    formData.append('course_registrations_id', rowDetails.courseRegistrationId); // Add both for backward compatibility
                }

                if (rowDetails.courseFeeId) {
                    formData.append('course_fee_id', rowDetails.courseFeeId);
                    formData.append('price', rowDetails.courseFeePrice);
                }

                if (!rowDetails.installmentId && !rowDetails.installmentScheduleId) {
                    formData.append('coupon_code', data.couponCode);
                }
                await bankTransferMutation.mutateAsync(formData);
            } else {
                const requestBody = getRequestedBody();
                await paymentMutation.mutateAsync(requestBody);
            }
        } catch (error) {
            return;
        } finally {
            setData(prev => ({ ...prev, cardLoading: false }));
        }
    };

    useEffect(() => {
        if ((paymentMutation.isSuccess || bankTransferMutation.isSuccess) && !error) {

            if (selectedPayment.payment === 'bank-transfer') {
                setTimeout(() => { navigate(`/${page}`); }, 500);
            }

            else {
                setRowDetails({
                    courseId: '',
                    courseOfferId: '',
                    courseOfferPrice: '',

                    // training-courses
                    discount: '',
                    thisUserId: '',
                    thisCompanyId: '',
                    courseRegistrationId: '',
                    userToken: '',
                    thisRowPrice: '',
                    theImgUploaded: '',
                    installmentId: '',
                    installmentScheduleId: '',

                    // course fees
                    courseFeeId: '',
                    courseFeePrice: ''
                });
                setSelectedPayment({
                    location: '', // where's course place ex: (الرياض / السعوديه)
                    currencyTitle: '', // currency title (SAR || ريال سعودي)
                    date: '', // date of course
                    duration: '', // duration in days
                    payment: '', // payment selection
                    paymentInAr: '',
                });
                window.open(resFromBank?.data?.InvoiceURL, '_blank');
                setTimeout(() => {
                    if (page === "training-courses") {
                        navigate(courseHref({ id, title: course?.title }));
                    } else {
                        navigate(`/offers`);
                    }
                    window.location.reload();
                }, 500);
            }
        }
    }, [paymentMutation.isSuccess, bankTransferMutation.isSuccess, error, selectedPayment.payment]);

    // for prevent reload
    useEffect(() => {
        const toPreventRefresh = (e) => {
            if ((paymentMutation.isSuccess || bankTransferMutation.isSuccess) && !error) {
                navigate(`/${page}`)
            } else {
                const confirmRefresh = window.confirm(
                    t('training-courses.lose-data')
                );
                if (confirmRefresh) {
                    navigate(`/${page}`);
                } else {
                    e.preventDefault();
                }
            }
        };
        window.addEventListener('beforeunload', toPreventRefresh);
        return () => {
            window.removeEventListener('beforeunload', toPreventRefresh);
        };
    }, [navigate, paymentMutation.isSuccess, bankTransferMutation.isSuccess, error]);

    useEffect(() => {
        const state = location?.state;
        if (state?.fromProfile) {
            setSelectedPayment(prev => ({
                ...prev,
                payment: state.payment || prev.payment,
                paymentInAr: state.paymentTitle || prev.paymentInAr,
                dueDate: state.dueDate || prev.dueDate || '',
                monthlyPayment: state.monthlyPayment || prev.monthlyPayment || '',
                installmentCount: state.installmentCount || prev.installmentCount || '',
                currentInstallmentNumber: state.currentInstallmentNumber || prev.currentInstallmentNumber || ''
            }));
            setRowDetails(prev => ({
                ...prev,
                courseId: String(state.courseId || prev.courseId || id || ''),
                thisRowPrice: String(state.price || prev.thisRowPrice || ''),
                totalPrice: String(state.totalPrice || prev.totalPrice || ''),
                courseRegistrationId: state.courseRegistrationId || prev.courseRegistrationId || '',
                installmentId: state.installmentId || prev.installmentId || '',
                installmentScheduleId: state.installmentScheduleId || prev.installmentScheduleId || ''
            }));

            // Auto-trigger fatoorah payment if specified
            if (state.autoTriggerPayment && state.payment === 'fatoorah') {
                setTimeout(() => {
                    const requestBody = {
                        installment_id: state.installmentId,
                        installment_schedule_id: state.installmentScheduleId,
                        course_id: state.courseId,
                        price: state.price
                    };
                    paymentMutation.mutate(requestBody);
                }, 1000); // Small delay to ensure state is set
            }
        }
        // run once on mount
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
        const state = location?.state;
        if (!rowDetails.courseId &&
            (page === "training-courses" &&
                (!rowDetails.courseRegistrationId && !rowDetails.courseFeeId)
            )
        ) {
            if (state?.fromProfile) return;
            navigate(courseHref({ id, title: course?.title }));
        }
    }, [rowDetails, page]);

    const getErrorMessage = () => {
        if (bankTransferMutation.error) {
            return bankTransferMutation.error.message || t('training-courses.bank-err');
        }
        if (paymentMutation.error) {
            return paymentMutation.error.message || t('training-courses.pay-err');
        }
        if (couponMutation.error && data.couponCode) {
            return couponMutation.error.message || t('training-courses.coupon-notvalid');
        }
        return null;
    };

    const copyIBAN = async () => {
        await navigator.clipboard.writeText(IBAN);
        toast({
            title: t('payment.iban-copied'),
            variant: "success"
        });
        setCopyIcon(<Check />)
        setTimeout(() => setCopyIcon(<Clipboard />), 1500);
    };

    return (
        <section className="grid lg:grid-cols-2 gap-2 border rounded-xl">

            <div className="p-3">
                <PaymentCourseBox
                    course={course}
                    selectedPayment={selectedPayment}
                    rowDetails={rowDetails}
                    page={page}
                    discountPercentage={data.discountPercentage}
                    discount={page === "offers" ? rowDetails?.discount : data.discount}
                    dueDate={selectedPayment?.dueDate}
                    monthlyPayment={selectedPayment?.monthlyPayment}
                    installmentId={rowDetails?.installmentId}
                    installmentCount={selectedPayment?.installmentCount}
                    currentInstallmentNumber={selectedPayment?.currentInstallmentNumber}
                    fromProfile={location?.state?.fromProfile || false}
                />
            </div>

            {/* CARD DATA */}
            <div className="p-3 lg:rounded-e-xl lg:border-e-2">
                {/* SELECTED PAYMENT METHOD */}
                <div className="flex items-center gap-2 mb-3">
                    <div>
                        <img src={IvoryLogo} alt="" className="w-6 mb-1" />
                    </div>
                    <h1 className="!text-start text-xl">
                        {selectedPayment?.paymentInAr}
                    </h1>
                </div>

                {/* price */}
                <div className="flex items-center justify-between">
                    <p className="max-w-64 md:max-w-80 truncate">{course?.title}</p>
                    <p className="text-base flex items-center gap-2">
                        {rowDetails?.thisRowPrice || rowDetails?.courseFeePrice || ""}
                        <SaudiRiyal size={16} />
                    </p>
                </div>

                {/* discount */}
                <div className="flex items-center justify-between my-1">
                    <p>{t('training-courses.discount')}</p>
                    <p>
                        {page === 'offers' ?
                            `% ${rowDetails?.discount}` || "0"
                            :
                            data.discount
                                ?
                                `${data?.discount}` || "0"
                                :
                                `% ${data?.discountPercentage}` || "0"
                        }
                    </p>
                </div>

                {/* vat */}
                <div className="flex items-center justify-between">
                    <p>{t('training-courses.vat')} ( {rowDetails?.taxPercentage || "0.00"} %)</p>
                    <p className="flex items-center gap-2">
                        {Number(rowDetails?.vat)?.toFixed(2) || ""}
                        <span>
                            <SaudiRiyal size={16} />
                        </span>
                    </p>
                </div>

                <div className="border-[1px] border-dashed border-b border-[#D9D9D9]" />

                {/* total amount */}
                <div className="flex items-center justify-between my-2">
                    <p>{t('training-courses.total')}</p>
                    <p className="text-base flex items-center gap-1">
                        {
                            page === 'offers' ?
                                `${rowDetails?.courseOfferPrice}` || ""
                                :
                                // data.discountPercentage ?
                                //     <>
                                //         {Number(rowDetails?.totalPrice) - (Number(rowDetails?.totalPrice) * (Number(data.discountPercentage) / 100))}
                                //     </>
                                //     :
                                //     data.discount ?
                                //         <>
                                //             {Number(rowDetails?.totalPrice) - Number(data.discount)}
                                //         </>
                                //         :
                                rowDetails?.courseFeePrice ?
                                    Number(rowDetails?.courseFeePrice)?.toFixed(2)
                                    :
                                    rowDetails?.installmentId && rowDetails?.installmentScheduleId ?
                                        Number(rowDetails?.thisRowPrice)?.toFixed(2)
                                        :
                                        Number(rowDetails?.totalPrice)?.toFixed(2)
                        }
                        <SaudiRiyal size={16} />
                    </p>
                </div>



                <form className="space-y-4" onSubmit={(e) => payFunc(e)}>
                    {selectedPayment.payment === 'bank-transfer' &&
                        <div className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="card-img" className="items-center gap-2 flex">
                                    <span>
                                        <img src={IvoryLogo} alt="" />
                                    </span>
                                    <span>{t('training-courses.invoice')}</span>
                                </Label>
                                <div className="relative">
                                    <Input
                                        type="file"
                                        accept="image/*"
                                        id="card-img"
                                        className={`border rounded-md p-2 w-full mt-2 bg-[#F5F5F5] focus:ring-1 focus:ring-[#E5E5E5] ${bankTransferMutation.error || data.imgErr ? 'ring-1 ring-red-500' : ''}`}
                                        onChange={(e) => setData((prev) => ({
                                            ...prev,
                                            imgUploaded: e.target.files[0],
                                            imgErr: null
                                        }))}
                                        required
                                    />
                                    <label htmlFor="card-img" className="absolute end-0 top-0 flex justify-center items-center bg-primary-tw h-10 w-16 cursor-pointer rounded-md">
                                        <Paperclip color="white" className="size-4" />
                                    </label>
                                </div>
                                {data.imgErr &&
                                    <span className="text-sm text-red-800 !text-start block">
                                        {data?.imgErr}
                                    </span>
                                }
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="card-img" className="items-center gap-2 flex">
                                    <span>
                                        <img src={IvoryLogo} alt="" />
                                    </span>
                                    <span>{t('payment.IBAN')}</span>
                                </Label>
                                <div className="relative">
                                    <Input
                                        value={IBAN}
                                        className="focus:ring-secondary-tw bg-[#F5F5F5]"
                                        readOnly
                                    />
                                    <Button
                                        type="button"
                                        className="absolute end-0 top-0 bg-primary-tw text-white transition-all w-16"
                                        variant="outline"
                                        onClick={copyIBAN}
                                    >
                                        {copyIcon}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    }
                    {
                        page !== "offers" &&
                        <div className="relative">
                            <Label htmlFor="coupon-code" className="items-center gap-2 flex">
                                <span>
                                    <img src={IvoryLogo} alt="" />
                                </span>
                                <span>{t('training-courses.coupon-code')}</span>
                            </Label>
                            <Input
                                type="text"
                                id="coupon-code"
                                disabled={couponMutation.isPending || couponMutation.isSuccess}
                                onKeyDown={(e) => {
                                    if (e.key === "Enter") {
                                        couponMutation.mutate()
                                    }
                                }}
                                className={`bg-[#F5F5F5] focus:ring-secondary-tw my-2 ${couponMutation.isError ? ' ring-red-600 ring-1' : ''}`}
                                onChange={(e) => setData(prev => ({ ...prev, couponCode: e.target.value, couponErr: null }))}
                            />
                            <Button type="button" variant="outline"
                                className="absolute end-0 top-[22px] w-16 bg-primary-tw text-white"
                                disabled={isLoading || !data.couponCode || couponMutation.isSuccess}
                                onClick={() => couponMutation.mutate()}
                            >
                                {
                                    couponMutation.isPending ?
                                        <Loader className="animate-spin" /> :
                                        couponMutation.isError ?
                                            <RefreshCcw />
                                            :
                                            couponMutation.isSuccess ?
                                                <Check />
                                                :
                                                t('custom.confirm')
                                }
                            </Button>
                        </div>
                    }
                    <div>
                        {/* {
                            (resFromBank?.data?.InvoiceURL && !error) &&
                            <Link to={resFromBank?.data?.InvoiceURL} className="pay-link">
                                {t('training-courses.continue-paying')}
                            </Link>
                        } */}
                        {
                            (resFromBank?.data?.payment_type === 'bank_transfer' && !data.couponErr && !error && !isLoading) &&
                            <div>
                                <p className="text-primary-tw">
                                    {t('training-courses.paying-done')}.
                                </p>
                            </div>
                        }
                    </div>
                    <button
                        type="submit"
                        disabled={bankTransferMutation.isPending || paymentMutation.isPending}
                        className="w-full py-2 bg-primary-tw text-white my-2 rounded-lg disabled:bg-primary-tw/70">
                        {(bankTransferMutation.isPending || paymentMutation.isPending) ?
                            <div className="flex justify-center items-center gap-2">
                                <span>{t('custom.checking')}</span>
                                <Loader className="animate-spin" />
                            </div>
                            :
                            (resFromBank?.InvoiceURL && !data.couponErr && !data.couponCode)
                                ?
                                t('custom.done-check')
                                :
                                selectedPayment.payment === "bank-transfer" ?
                                    t('custom.check-payment')
                                    :
                                    t('custom.checktab')
                        }
                    </button>
                    {getErrorMessage() && (
                        <p className="text-red-600 text-sm !text-start p-2 bg-red-50 rounded-md border border-red-200">
                            {getErrorMessage()}
                        </p>
                    )}
                    {/* {(paymentMutation.data?.InvoiceURL || bankTransferMutation.data?.InvoiceURL) && (
                        <p className="text-green-600 text-sm !text-start p-2 bg-green-50 rounded-md border border-green-200">
                            {t('training-courses.paying-done')}.
                        </p>
                    )} */}
                </form>
            </div>
        </section>
    );
};

export default PaymentCard;