"use client"
import Image from "next/image";
import { URL_IMAGE } from "@/utils/url";
import { Program } from "@/types/models";

import { useCart } from "@/contexts/cart";
import { useLocale, useTranslations } from "next-intl";
import { Link, usePathname } from "@/i18n/navigation";

import { Calendar, Clock, Loader, MapPin, SaudiRiyal, ShoppingCart, UserPen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

import { canBuyCourse } from "@/utils/course-status";
import { CountdownTimer } from "../../offers/_components/countdown";

export function ProgramBox({ program }: { program: Program }) {
    const { addToCart, itemIdAdding } = useCart();
    const t = useTranslations();
    const locale = useLocale();
    const pathname = usePathname();
    const isOffersPage = pathname.includes('/offers');
    const isHomePage = pathname === '/';
    const showCounter = isOffersPage || isHomePage;

    const type = program?.type ?? program?.course?.type;

    // Use the prioritised type for date logic
    const canBuy = canBuyCourse(program?.start_date, program?.end_date, type);

    const isOnline = type === 'online';

    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 programLink = `/programs/${program?.id}${programSlug ? `/${programSlug}` : ''}`;

    return (
        <div className="flex flex-col h-full border rounded-md bg-white shadow-sm overflow-hidden">

            <div className="w-full h-48 relative overflow-hidden shrink-0">
                <Link href={programLink}>
                    {
                        program?.image ? (
                            <>
                                <Image
                                    src={`${URL_IMAGE}/${program?.image}`}
                                    alt={program?.name}
                                    className="size-full object-cover rounded-t-md hover:scale-105 transition"
                                    width={250}
                                    height={250}
                                />
                                {(program?.discount_amount ?? 0) > 0 && (
                                    <Badge className="absolute top-2 right-2 bg-primary-tw-600 text-white border-none px-2 py-0.5 text-xs font-bold z-10">
                                        -{Math.round(((program?.discount_amount ?? 0) / (program.price || 1)) * 100)}%
                                    </Badge>
                                )}
                            </>
                        ) :
                            <span className="bg-gray-200 w-full h-48 block rounded-t-md flex items-center justify-center font-bold text-gray-400">
لا توجد صورة                            </span>
                    }

                    {showCounter && program?.promotion?.start_at && (
                        <div className="absolute bottom-0 inset-x-0 z-20 bg-gradient-to-t from-primary-tw-600/90 to-primary-tw-600/70 backdrop-blur-sm p-2 text-white border-t border-white/20">
                            <div className="flex items-center justify-between gap-2 max-w-full">
                                <div className="flex items-center gap-1.5 shrink-0">
                                    <Clock className="size-3" />
                                    <span className="text-[10px] font-black uppercase tracking-widest">{t("custom.offer_period") || "Offer Period"}</span>
                                </div>
                                <div className="bg-white/10 rounded-lg px-2 py-0.5">
                                    <CountdownTimer targetDate={program.promotion.end_at!} />
                                </div>
                            </div>
                        </div>
                    )}
                </Link>
            </div>

            <div className="p-3 flex-1 flex flex-col">
                <Link scroll={true} href={programLink} className="text-lg font-semibold line-clamp-2 min-h-[3.5rem] mb-2">
                    {locale === 'ar' ? program?.name_an || program?.name : program?.name || program?.name_an}
                </Link>

                <hr className="mb-3 opacity-50" />

                {program?.description && (
                    <>
                        <Link scroll={true} href={programLink} className="line-clamp-2 text-gray-500 text-sm mb-4 min-h-[2.5rem]">
                            {program.description}
                        </Link>
                        <hr className="mb-3 opacity-50" />
                    </>
                )}

                <div className="space-y-3 mb-4 flex-1">
                    {/* start date */}
                    {isOnline && program?.start_date && (
                        <div className="flex items-center gap-2 text-gray-600">
                            <Calendar className="size-4 shrink-0" />
                            <span className="text-sm">
                                {program.start_date} {program.end_date && program.end_date !== program.start_date && ` - ${program.end_date}`}
                            </span>
                        </div>
                    )}

                    {/* instructor */}
                    <div className="flex items-center gap-2 text-gray-600">
                        <UserPen className="size-4 shrink-0" />
                        <span className="text-sm">
                            {(() => {
                                const c = program?.coaches?.[0];
                                const parts = [c?.first_name, c?.fourth_name || c?.second_name];
                                return parts.filter(Boolean).join(" ") || t("programs.instructor");
                            })()}
                        </span>
                    </div>

                    {/* online or ofline */}
                    <div className="flex items-center gap-2 text-gray-600">
                        <MapPin className="size-4 shrink-0" />
                        <span className="text-sm">
                            {type === 'record' ? t("programs.recorded") : isOnline ? t("custom.online") : t("custom.classroom")}
                        </span>
                    </div>
                </div>

                <div className="mt-auto pt-3 border-t">
                    <div className="flex items-center justify-between min-h-10">
                        {
                            program?.price ? (
                                <>
                                    {canBuy ? (
                                        <Button
                                            variant={"secondary"}
                                            disabled={!!itemIdAdding}
                                            onClick={(e) => {
                                                e.preventDefault();
                                                addToCart(program?.id, t);
                                            }}
                                            className="text-primary-tw-700"
                                        >
                                            {
                                                (itemIdAdding === program?.id) ?
                                                    <Loader className='animate-spin' />
                                                    :
                                                    <ShoppingCart />
                                            }
                                        </Button>
                                    ) : (
                                        <span className="text-gray-500 text-sm font-semibold whitespace-nowrap overflow-hidden text-ellipsis">
                                            {t("programs.ended")}
                                        </span>
                                    )}
                                    <div className="flex flex-col items-end">
                                        {(program?.promotion || program?.discount_amount) ? (
                                            <>
                                                <span className="text-primary-tw-600 text-lg font-bold flex items-center gap-1 leading-none">
                                                    {program.promotion?.final_price || ((program.price || 0) - (program.discount_amount || 0))} <SaudiRiyal className="size-4" />
                                                </span>
                                                <del className="text-gray-400 text-xs font-medium">
                                                    {program.price}
                                                </del>
                                            </>
                                        ) : (
                                            <span className="text-primary-tw-600 text-lg font-semibold flex items-center gap-1">
                                                {program?.price} <SaudiRiyal className="size-5" />
                                            </span>
                                        )}
                                    </div>
                                </>
                            ) : (
                                <span className={`font-semibold flex items-center gap-1 w-full text-center ${!canBuy ? 'text-gray-500' : 'text-green-600'}`}>
                                    {canBuy ? t("programs.free") : t("programs.ended")}
                                </span>
                            )
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}