"use client"

import { useState } from 'react';
import { Program } from '@/types/models';
import { canBuyCourse } from '@/utils/course-status';
import { useFormSubmission } from '@/hooks/use-form-submission';
import { useLocale, useTranslations } from 'next-intl';
import { useCart } from '@/contexts/cart';
import { Link, useRouter } from '@/i18n/navigation';
import { toast } from '@/hooks/use-toast';

import { Clock, BookOpen, Users, Tag, HelpCircle, Globe, Award, Trophy, Unlock, Loader, SaudiRiyal, MapPin } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { revalidate } from '@/utils/revalidate';
import { useMutation } from '@tanstack/react-query';
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { CountdownTimer } from "../../offers/_components/countdown";

export function ProgramAside({ program, userHasThisProgram, sessions }: { program: Program, userHasThisProgram: boolean, sessions?: any[] }) {
    const t = useTranslations();
    const locale = useLocale();
    const router = useRouter();

    const { addToCart, itemIdAdding } = useCart();

    // Priority should be given to the group's (program's) type.
    const courseType = program?.type ?? program?.course?.type;
    // earliest session start_date determines when the course kicks off
    const earliestStartDate = sessions?.length
        ? sessions
            .map(s => s.start_date)
            .filter(Boolean)
            .sort()[0]
        : program?.start_date;

    const canBuy = canBuyCourse(earliestStartDate, program?.end_date, courseType);

    const [couponCode, setCouponCode] = useState("");
    const [subTotal, setSubTotal] = useState({
        old: Number(program?.price),
        new: program?.promotion ? String(program.promotion.final_price) : ""
    });

    const handleWatchClick = () => {
        const token = USER_TOKEN_CL();
        const watchUrl = `/dashboard/programs/fullscreen-${program?.id}`;
        
        if (!token) {
            router.push(`/login?redirect=${watchUrl}`);
            return;
        }

        router.push(watchUrl);
    };

    const courseDetails = [
        { label: 'duration', data: `${program?.hours} ${t("custom.hours")}`, icon: Clock, see: true },
        // { label: 'lectures', data: "", icon: BookOpen, see: true },
        // { label: 'enrolled', data: "", icon: Users, see: true },
        { label: 'category', data: `${program?.course?.category?.name}`, icon: Tag, see: true },
        // { label: 'quizzes', data: "", icon: HelpCircle },
        { label: 'language', data: t(`custom.${program?.langue}`), icon: Globe, see: true },
        // { label: 'skillLevel', data: "", icon: Award, see: true },
        // { label: 'certificate', data: "", icon: Trophy, see: Boolean(program?.certificate_pro) },
        // { label: 'certificate', data: "(certificate_pro)", icon: Trophy, see: true },
        // { label: 'certificate', data: "", icon: Trophy, see: true },
        // { label: 'access', data: "", icon: Unlock, see: true }
        { label: 'type_filter', data: t(`programs.${courseType === 'record' ? 'recorded' : 'online'}`), icon: MapPin, see: true },
    ];

    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"
                });

            } else {
                setSubTotal(prev => ({
                    ...prev,
                    new: total
                }));

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

    const ifProgramIsFree = useFormSubmission({
        endPoint: `/user/groups/take/free/${program?.id}`,
        method: "POST",
        onError: (err) => {
            if (err) {
                const message = err?.response?.data?.message;
                toast({
                    variant: "destructive",
                    title: message
                });
                return { handled: true }
            }
        },
        onSuccess: (res) => {
            const message = res?.message;
            const status = res?.status;


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

    const addToCartAction = async () => {
        try {
            const token = USER_TOKEN_CL();
            const programName = locale === 'ar' ? program?.name_an || program?.name : program?.name || program?.name_an;
            const programSlug = programName ? encodeURIComponent(programName.trim().toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')) : '';
            const programUrl = `/programs/${program?.id}${programSlug ? `/${programSlug}` : ''}`;

            if (!token) {
                router.push(`/login?redirect=${programUrl}`);
                return "unauthorized";
            }

            if (program?.price) {
                await new Promise((resolve, reject) => {
                    addToCart(
                        program?.id,
                        t,
                        () => resolve("money"),
                        () => reject(new Error("Cart addition failed"))
                    );
                });
                return "money";
            } else {
                await ifProgramIsFree.mutateAsync({});
                return "free";
            }
        } catch (error) {
            throw error;
        }
    };

    const buyNow = useMutation({
        mutationKey: [`program-${program?.id}`],
        mutationFn: async () => {
            const result = await addToCartAction();

            if (result === "free") {
                revalidate({ url: `/user/groups/records` });
                router.push(`/dashboard/programs/fullscreen-${program?.id}`);
                
            } else if (result === "money") {
                router.push("/cart/checkout");
            }

            return result;
        }
    });

    const buyByPoints = useFormSubmission({
        endPoint: `/cart/points-payment/${program?.id}`,
        method: "POST",
        onSuccess: (res) => {
            if (res?.status) {
                toast({
                    variant: "success",
                    title: res.message
                });
                revalidate({ url: `/user/groups/records` });
                // We reload to update the UI (hide point button, show watch button)
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                toast({
                    variant: "destructive",
                    title: res?.message || "Error"
                });
            }
        },
        onError: (err) => {
            if (err) {
                const message = err?.response?.data?.message;
                toast({
                    variant: "destructive",
                    title: message || (err as any)?.message || "Error"
                });
                return { handled: true }
            }
        }
    });

    return (
        <div className="w-full bg-white m-auto rounded-lg shadow-sm border p-6 lg:w-96 sticky top-2 z-30">
            {/* video preview */}
            {(program as any)?.video && (
                <div className="mb-6">
                    <div className="relative w-full pb-[56.25%] rounded-lg overflow-hidden bg-gray-100">
                        <iframe
                            src={(program as any).video.includes('youtube') ? 
                                (program as any).video.replace('watch?v=', 'embed/') : 
                                (program as any).video}
                            className="absolute top-0 left-0 w-full h-full border-0"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                            allowFullScreen
                            title={program.name}
                        />
                    </div>
                </div>
            )}

            {/* Promo Counter */}
            {program?.promotion?.end_at && (
                <div className="mb-6 p-4 bg-gradient-to-br from-primary-tw-50 to-white rounded-xl border border-primary-tw-100 shadow-sm flex justify-between">
                    <div className="flex items-center gap-2 mb-3">
                        <div className="size-6 rounded-lg bg-primary-tw-600 flex items-center justify-center text-white">
                            <Clock className="size-3.5" />
                        </div>
                        <span className="text-xs font-black text-primary-tw-700 uppercase tracking-wider">
                            {t("custom.offer_period") || "Offer Period"}
                        </span>
                    </div>
                    <div className="flex justify-center">
                        <CountdownTimer targetDate={program.promotion.end_at} />
                    </div>
                </div>
            )}

            {/* price */}
            <div className="mb-6">
                <div className="flex flex-col gap-2">
                    {
                        subTotal.new ?
                            <div className="flex items-center justify-between gap-3 w-full">
                                <div className="flex flex-col">
                                    <span className="font-bold text-3xl text-primary-tw-700 flex items-center gap-1">
                                       {subTotal?.new || "0"}  <SaudiRiyal className="size-6" />
                                    </span>
                                    <del className="text-gray-400 text-sm font-medium flex items-center gap-1">
                                        {t("programs.price")} {subTotal?.old} <SaudiRiyal className="size-3" />
                                    </del>
                                </div>
                                {program?.promotion && (
                                    <Badge className="bg-red-600 text-white border-none px-2 py-0.5 text-xs font-black rounded-lg animate-pulse shadow-sm">
                                        -{program.promotion.type === 'percentage' ? `${program.promotion.value}%` : <span className="flex items-center gap-0.5">{program.promotion.value} <SaudiRiyal className="size-3" /></span>}
                                    </Badge>
                                )}
                            </div>
                            :
                            <span className="font-bold text-3xl text-primary-tw-700 flex items-center gap-1">
                                {program?.price ? String(subTotal?.old) : t("programs.free")}
                                {program?.price ? <SaudiRiyal className="size-6" /> : ""}
                            </span>
                    }
                </div>
            </div>

            {/* Buy with Points */}
            {!(userHasThisProgram || program?.has_group) && program?.buy_by_point && program?.price && (
                <div className="mb-4">
                    <Button
                        variant="outline"
                        className="w-full border-emerald-600 text-emerald-600 hover:bg-emerald-50 font-black flex flex-col items-center py-2 h-auto gap-0.5"
                        onClick={() => buyByPoints.mutate(program?.points_payment_payload || { purchase_type: "group" })}
                        disabled={buyByPoints.isPending}
                    >
                        {buyByPoints.isPending ? (
                            <Loader className="animate-spin size-4" />
                        ) : (
                            <>
                                <span className="text-sm">شراء بواسطة النقاط</span>
                                <span className="text-[10px] font-bold opacity-70 italic">
                                    التكلفة: {program.points_cost} نقطة
                                </span>
                            </>
                        )}
                    </Button>
                </div>
            )}

            {/* buy now - add to cart */}
            {
                (userHasThisProgram || program?.has_group) ?
                    <div className="space-y-2 mb-6">
                        <Button 
                            className='bg-primary-tw-600 w-full hover:opacity-85 font-black'
                            onClick={handleWatchClick}
                        >
                            {t("programs.watch") || "مشاهدة الدورة"}
                        </Button>
                    </div>
                    :
                    canBuy ? (
                        <div className="space-y-2 mb-6">
                            {
                                program?.price ?
                                    <Button
                                        disabled={!buyNow.isPending && itemIdAdding === program?.id}
                                        onClick={() => addToCartAction()}
                                        className='bg-primary-tw-600 w-full hover:opacity-85'
                                    >
                                        {
                                            !buyNow.isPending && itemIdAdding === program?.id ?
                                                <>
                                                    <Loader className='animate-spin' />
                                                    {t("custom.adding")}
                                                </>
                                                :
                                                t("custom.add to cart")
                                        }
                                    </Button>
                                    :
                                    null
                            }
                            <Button
                                variant={"secondary"}
                                disabled={buyNow.isPending}
                                onClick={() => buyNow.mutate()}
                                className='w-full capitalize'
                            >
                                {
                                    buyNow.isPending ?
                                        <>
                                            <Loader className='animate-spin' />
                                            {t("custom.buying")}
                                        </>
                                        :
                                        program?.price ?
                                            t("custom.buy now")
                                            :
                                            t("custom.free buy now")
                                }
                            </Button>
                        </div>
                    ) : (
                        <div className="space-y-2 mb-6">
                            <Button
                                disabled
                                className='bg-gray-400 w-full hover:bg-gray-400 cursor-not-allowed'
                            >
                                {t("programs.ended")}
                            </Button>
                        </div>
                    )
            }

            {/* program details */}
            <div className="space-y-4 mb-6">
                {courseDetails.map((item, index) => {
                    const Icon = item.icon;
                    return item?.see && (
                        <div key={index} className="flex items-center gap-2 text-gray-700 font-semibold">
                            <Icon className="size-4 text-purple-600 flex-shrink-0" />
                            <span className="text-sm">{t(`programs.${item.label}`)} {item.data}</span>
                        </div>
                    );
                })}
            </div>

            {/* coupon */}
            {/* <div className="mt-6">
                <p className="text-gray-700 font-medium mb-3">{t("custom.have coupon")}</p>
                <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>
            </div> */}
        </div>
    );
}