"use client";

import Image from "next/image";
import { BillingTypo, CheckoutContentTypo } from "@/types";

import { useEffect, useMemo, useState } from "react";
import { useFormSubmission } from "@/hooks/use-form-submission";
import { useLocale, useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { toast } from "@/hooks/use-toast";
import { useGet } from "@/hooks/use-get";
import { URL_IMAGE } from "@/utils/url";
import { Loader, SaudiRiyal } from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

export function OrderSummary({
    checkout,
    form
}: CheckoutContentTypo & BillingTypo) {
    const t = useTranslations();
    const locale = useLocale();
    const [agreed, setAgreed] = useState(false);

    const [couponCode, setCouponCode] = useState("");
    const [subTotal, setSubTotal] = useState({
        old: Number(checkout?.cart?.total) || 0,
        new: ""
    });

    useEffect(() => {
        const newTotal = Number(checkout?.cart?.total) || 0;
        setSubTotal(prev => ({
            ...prev,
            old: newTotal,
            ...(newTotal === 0 ? { new: "" } : {})
        }));
        if (newTotal === 0) {
            setCouponCode("");
            form?.setValue("couponCode", "");
        }
    }, [checkout?.cart?.total, form]);

    const { data: taxData } = useGet({ url: "/tax-value", context: "dashboard" });

    const taxValue = taxData?.data?.tax_value?.content ? Number(taxData?.data?.tax_value?.content) : 0;
    const isTaxExempt = taxData?.is_tax_exempt;

    const currentSubTotal = Number(subTotal.new || subTotal.old) || 0;
    const taxAmount = (isTaxExempt || currentSubTotal === 0) ? 0 : (currentSubTotal * taxValue) / (100 + taxValue);
    const totalPayable = currentSubTotal;

    const hasItems = !!(checkout?.cart?.items?.length);

    const couponCodeFn = useFormSubmission({
        endPoint: "/cart/apply-coupon",
        method: "POST",
        onError: () => {
            return { handled: true }
        },
        onSuccess: (response) => {
            const status = response?.status;
            const message = response?.message;
            const total = response?.total;

            if (status === "warning") {
                toast({
                    title: message,
                    variant: "destructive"
                });

                form?.setValue("couponCode", "");
            } else {
                form?.setValue("couponCode", total);
                setSubTotal(prev => ({
                    ...prev,
                    new: total
                }));

                toast({
                    title: message,
                    variant: "success"
                });
            }
        }
    });

    const selectedWay = form?.watch("way");

    const checkoutLink = useMemo(() => {
        switch (selectedWay) {
            // case "bank_transfer":
            //     return "/cart/offline-payment";
            case "fatoorah":
                return "/cart/fatoorahPay";
            case "tabby":
                return "/cart/tabby";
            // case "jeel":
            //     return "/cart/jeel";
            default:
                return "";
        }
    }, [selectedWay]);

    const getCheckoutBody = () => {
        switch (selectedWay) {
            // case "bank_transfer":
            //     return {
            //         image: form?.getValues("image")
            //     };

            case "fatoorah":
                return {
                    email: form?.getValues()?.email,
                    name: form?.getValues()?.name,
                    phone: form?.getValues()?.phone,
                };

            case "tabby":
                return {
                    email: form?.getValues()?.email,
                    name: form?.getValues()?.name,
                    phone: form?.getValues()?.phone,
                };

            // case "jeel":
            //     return {
            //         email: form?.getValues()?.email,
            //         phone: form?.getValues()?.phone,
            //         first_name: form?.getValues()?.first_name,
            //         last_name: form?.getValues()?.last_name,
            //         national_id: form?.getValues()?.national_id,
            //     };

            default:
                throw new Error("Invalid payment way");
        }
    };

    const checkoutFnc = useFormSubmission({
        endPoint: checkoutLink,
        method: "POST",
        onSuccess: (response) => {
            const message: string = response?.message;
            const status: boolean = response?.status;
            const paymentURL = response?.url;

            toast({
                variant: status ? "success" : "destructive",
                title: message || t("custom.done"),
                className: "capitalize"
            });

            if (status) {
                if (paymentURL) {
                    if (["fatoorah", "tabby", "jeel"].includes(selectedWay || "")) {
                        window.open(paymentURL, "_self");
                    } else {
                        window.location.href = paymentURL;
                    }
                } else {
                    setTimeout(() => {
                        window.location.href = "/success-payment";
                    }, 1500);
                }
            }

        }
    });

    const onCheckout = () => {
        form?.trigger();
        const body = getCheckoutBody();

        const anyItemOfBodyIsEmpty = Object.values(body).some(
            i => i === null || i === undefined || i === ""
        );

        if (anyItemOfBodyIsEmpty) {
            toast({
                variant: "destructive",
                title: t("checkout.please fill")
            });
            return;
        };

        // if (form?.getValues("way") === "bank_transfer") {
        //     const image = form.getValues("image")?.[0];
        //     if (!image) {
        //         toast({
        //             variant: "destructive",
        //             title: t("checkout.please upload image")
        //         });
        //         return;
        //     }
        //     const formData = new FormData();
        //     formData.append("image", image);
        //     formData.append("coupon", form?.watch("couponCode") || "");
        //     checkoutFnc.mutate(formData);
        //     return;
        // }

        checkoutFnc.mutate({
            ...body,
            coupon: form?.watch("couponCode")
        });
    };

    return (
        <Card className="sticky top-4">
            <CardHeader>
                <CardTitle className="text-2xl">{t("checkout.yourOrder")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
                {/* items of order */}
                <div className="space-y-4 max-h-40 overflow-y-scroll">
                    {
                        checkout?.cart?.items?.length ?
                            checkout?.cart?.items?.map((item,i) => {
                                // NEW DISCOVERY: Data is nested under 'group' or 'package'
                                const itemName = item?.package?.name || item?.group?.name || item?.package_name || item?.group_name || item?.name || 'Item Details';
                                const itemImg = item?.package?.image || item?.group?.image || item?.package_image || item?.group_image ;
                                const itemPrice = item?.package?.price || item?.group?.price || item?.price || 0;
                                let itemLink = '';
                                if (item?.package?.id) {
                                    const pkgName = item?.package?.name || itemName;
                                    const pkgSlug = pkgName ? encodeURIComponent(pkgName.trim().toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')) : '';
                                    itemLink = `/programs/packages/${item.package.id}${pkgSlug ? `/${pkgSlug}` : ''}`;
                                } else {
                                    const progName = item?.group?.name || itemName;
                                    const progSlug = progName ? encodeURIComponent(progName.trim().toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')) : '';
                                    itemLink = `/programs/${item?.group?.id || ''}${progSlug ? `/${progSlug}` : ''}`;
                                }

                                return (
                                <div key={item.id} className="flex gap-4 pb-4 border-b last:border-0">
                                    <div className="relative size-10 flex-shrink-0 rounded-md overflow-hidden bg-zinc-50 border border-zinc-100 flex items-center justify-center">
                                        {
                                            itemImg ?
                                                <img
                                                    src={`https://tr.ivorytraining.com/${String(itemImg).replace(/^\/+/, '')}`}
                                                    alt={itemName}
                                                    className="w-full h-full object-cover rounded-md"
                                                />
                                                :
                                                <div className="size-full flex items-center  text-primary-tw-600 font-bold text-xl justify-center bg-zinc-100">
                                                    {i+1}
                                                </div>
                                        }
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <Link href={itemLink} className="font-bold text-base mb-1 line-clamp-2 hover:text-primary-tw-600 transition-colors">
                                            {itemName}
                                        </Link>
                                        <div className="flex items-center gap-1">
                                            <p className="font-black text-primary-tw-700">
                                                {Number(itemPrice).toFixed(2)}
                                            </p>
                                             <SaudiRiyal className="size-4 text-primary-tw-600" />
                                        </div>
                                    </div>
                                </div>
                            )})
                            :
                            <div className="grid place-items-center">
                                <p>
                                    {t('custom.no results')}
                                </p>
                            </div>
                    }
                </div>

                {/* subTotal */}
                <div className="flex justify-between items-start text-lg">
                    <p className="font-semibold">{t("checkout.subtotal")}</p>
                    {
                        subTotal.new ?
                            <div className="grid place-items-end">
                                <span className="font-bold text-xl flex items-center gap-1">
                                    <SaudiRiyal className="size-5" /> {subTotal.new ? subTotal.new : "0"}
                                </span>
                                <del className="text-gray-700">
                                    {subTotal.old}
                                </del>
                            </div>
                            :
                            <span className="font-bold text-xl flex items-center gap-1">
                               {subTotal.old ? subTotal.old : "0"}  <SaudiRiyal className="size-5" /> 
                            </span>
                    }
                </div>

                {/* coupon */}
                <div className="flex gap-2">
                    <Input
                        placeholder={t("checkout.enterCouponCode")}
                        value={couponCode}
                        onChange={(e) => setCouponCode(e.target.value)}
                        className="flex-1"
                    />
                    <Button
                        type="button"
                        onClick={() => couponCodeFn.mutate({ coupon: couponCode })}
                        variant="default"
                        disabled={!couponCode || couponCodeFn.isPending}
                        className="bg-primary-tw-700"
                    >
                        {couponCodeFn.isPending ?
                            <>
                                <Loader className=" animate-spin" />
                                {t("custom.applying")}
                            </>
                            :
                            t("custom.apply")}
                    </Button>
                </div>

                {/* tax — only show when cart has items */}
                {hasItems && !isTaxExempt && taxValue > 0 && (
                    <div className="flex justify-between items-center text-sm text-gray-600">
                        <span className="font-medium">
                            {t("checkout.tax")} ({taxValue}%)
                        </span>
                        <span className="font-semibold flex items-center gap-1">
                            {taxAmount?.toFixed(2)}
                            <SaudiRiyal className="size-4" />
                        </span>
                    </div>
                )}

                {/* {!isTaxExempt && taxValue > 0 && (
                    <p className="text-xs text-green-600 font-medium -mt-4">
                        {t("checkout.price_inclusive_tax") || "Price inclusive of tax"}
                    </p>
                )} */}

                {/* payable */}
                <div className="flex justify-between items-start pt-4 border-t text-lg">
                    <div className="font-semibold">
                        {t("checkout.payableAmount")}
                        {!isTaxExempt && taxValue > 0 && (
                            <p className="text-xs text-gray-600 font-medium mt-1">
                                {t("checkout.price_inclusive_tax") || "Price inclusive of tax"}
                            </p>
                        )}
                    </div>

                    <div className="grid place-items-end">
                        <span className="font-bold text-xl flex items-center gap-1 text-primary-tw-700">
                             {totalPayable?.toFixed(2)} <SaudiRiyal className="size-5" />
                        </span>
                        {subTotal.new && (
                            <del className="text-gray-400 text-sm">
                                {Number(subTotal.old).toFixed(2)}
                            </del>
                        )}
                    </div>
                </div>

                {/* note */}
                <p className="text-sm text-muted-foreground leading-relaxed">
                    {t("checkout.privacyNotice")}
                </p>

                {/* terms */}
                <div className="flex items-start gap-3">
                    <Checkbox
                        checked={agreed}
                        onCheckedChange={(checked: boolean) => setAgreed(checked)}
                        id="terms"
                        className="mt-0.5"
                    />
                    <label
                        htmlFor="terms"
                        className="text-sm leading-relaxed cursor-pointer"
                    >
                        {t("checkout.agreeToTerms")}{" "}
                        <Link
                            href="/privacy#terms"
                            className="text-primary-tw-500 underline font-medium"
                        >
                            {t("checkout.termsOfService")}
                        </Link>
                        {", "}
                        <Link
                            href="/privacy"
                            className="text-primary-tw-500 underline font-medium"
                        >
                            {t("checkout.privacyPolicy")}
                        </Link>{" "}
                        {t("checkout.and")}{" "}
                        <Link
                            href="/privacy#refund"
                            className="text-primary-tw-500 underline font-medium"
                        >
                            {t("checkout.refundPolicy")}
                        </Link>
                    </label>
                </div>

                {/* warn */}
                {/* <p className="text-sm text-destructive font-medium">
                    {t("checkout.pleaseAgree")}
                </p> */}

                {/* order btn */}
                <Button
                    type="submit"
                    form="checkout"
                    onClick={onCheckout}
                    className="w-full text-base"
                    disabled={!hasItems || !agreed || checkoutFnc.isPending}
                >
                    {checkoutFnc.isPending ?
                        <>
                            <Loader className=" animate-spin" />
                            {t("custom.submitting")}
                        </>
                        :
                        t("checkout.placeAnOrder")}
                </Button>
            </CardContent>
        </Card>
    );
}