"use client";

import Image from "next/image";
import { SaudiRiyal, ShoppingBag, Sparkles, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Badge } from "@/components/ui/badge";
import { URL_IMAGE, BASE_URL } from "@/utils/url";
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { toast } from "@/hooks/use-toast";
import axios from "axios";
import { useState } from "react";

export function PurchaseCard({ history }: { history: any }) {
    const t = useTranslations();
    const [isLoadingInvoice, setIsLoadingInvoice] = useState(false);

    const handleCardClick = async () => {
        if (isLoadingInvoice) return;
        
        setIsLoadingInvoice(true);
        try {
            const response = await axios.get(`${BASE_URL}/payment/fatoorah-invoice/${history.id}`, {
                headers: {
                    Authorization: `Bearer ${USER_TOKEN_CL()}`
                }
            });

            if (response.data?.status && response.data?.url) {
                window.open(response.data.url, '_blank');
            }
        } catch (error: any) {
            const errorMessage = error.response?.data?.message;
            // Only show toast if it's NOT the specific "no invoice" message
            if (errorMessage !== "لا توجد فاتورة متاحة لهذا الدفع") {
                toast({
                    variant: "destructive",
                    title: errorMessage || "حدث خطأ أثناء محاولة جلب الفاتورة",
                });
            }
        } finally {
            setIsLoadingInvoice(false);
        }
    };

    return (
        <div 
            onClick={handleCardClick}
            className="group relative h-full flex flex-col overflow-hidden bg-gradient-to-br from-white to-gray-50 dark:from-zinc-900 dark:to-zinc-950 rounded-2xl border border-gray-200 dark:border-zinc-800 hover:border-primary-tw-300 dark:hover:border-primary-tw-600 transition-all duration-500 hover:shadow-2xl hover:-translate-y-2 cursor-pointer"
        >
            {/* Loading Overlay */}
            {isLoadingInvoice && (
                <div className="absolute inset-0 z-50 bg-white/40 dark:bg-black/40 backdrop-blur-[2px] flex items-center justify-center rounded-2xl">
                    <Loader2 className="size-10 text-primary-tw-600 animate-spin" />
                </div>
            )}

            {/* Background decoration */}
            <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-primary-tw-100/20 to-purple-100/20 dark:from-primary-tw-900/10 dark:to-purple-900/10 rounded-full blur-3xl -translate-y-16 translate-x-16 group-hover:scale-150 transition-transform duration-700" />
            
            {/* Image Section */}
            <div className="relative h-56 w-full overflow-hidden rounded-t-2xl bg-gradient-to-br from-gray-100 to-gray-200 dark:from-zinc-800 dark:to-zinc-900">
                {history?.group?.image ? (
                    <>
                        <Image
                            src={`${URL_IMAGE}/${history.group?.image}`}
                            alt={history.group?.name}
                            fill
                            className="object-cover transition-transform duration-700 group-hover:scale-110"
                            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                        />
                        {/* Gradient overlay */}
                        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent opacity-80 group-hover:opacity-90 transition-opacity duration-500" />
                    </>
                ) : (
                    <div className="size-full flex items-center justify-center bg-gradient-to-br from-primary-tw-100 to-purple-100 dark:from-primary-tw-950 dark:to-purple-950">
                        <ShoppingBag className="size-16 text-primary-tw-400 opacity-30" />
                    </div>
                )}
                
                {/* Sparkles decoration */}
                <div className="absolute top-4 left-4 opacity-20 group-hover:opacity-40 transition-opacity duration-500">
                    <Sparkles className="size-5 text-white" />
                </div>
                
                {/* Status Badge - Floating top right */}
                <div className="absolute top-4 right-4 z-10">
                    <Badge 
                        className={`
                            font-bold px-3 py-1.5 shadow-lg backdrop-blur-md border
                            ${history?.status === 'completed' || history?.status === 'مكتمل' 
                                ? 'bg-green-100/90 text-green-700 dark:bg-green-950/90 dark:text-green-400 border-green-200 dark:border-green-900' 
                                : history?.status === 'pending' || history?.status === 'معلق'
                                ? 'bg-yellow-100/90 text-yellow-700 dark:bg-yellow-950/90 dark:text-yellow-400 border-yellow-200 dark:border-yellow-900'
                                : 'bg-gray-100/90 text-gray-700 dark:bg-gray-800/90 dark:text-gray-400 border-gray-200 dark:border-gray-700'
                            }
                        `}
                    >
                        {history?.status}
                    </Badge>
                </div>
            </div>

            {/* Content Section */}
            <div className="relative z-10 flex-1 flex flex-col p-6 space-y-4">
                {/* Title */}
                <div className="space-y-2 border-b border-gray-100 dark:border-zinc-800 pb-4">
                    <h3 className="font-bold text-xl text-gray-900 dark:text-gray-100 line-clamp-2 leading-tight">
                        {history?.group?.name}
                    </h3>
                </div>

                {/* Details Grid */}
                <div className="flex-1 space-y-3">
                    {/* Price */}
                    {Number(history?.price) ? (
                        <div className="flex items-center gap-3 group/item">
                            <div className="flex items-center justify-center size-10 rounded-xl bg-green-50 dark:bg-green-950/30 text-green-600 dark:text-green-400 group-hover/item:bg-green-100 dark:group-hover/item:bg-green-900/40 transition-colors shadow-sm">
                                <SaudiRiyal className="size-5" />
                            </div>
                            <div className="flex-1 min-w-0">
                                <p className="text-xs text-gray-500 dark:text-gray-400 font-medium uppercase tracking-wider">
                                    السعر
                                </p>
                                <p className="text-lg font-bold text-gray-900 dark:text-gray-100">
                                    {history?.price} ريال
                                </p>
                            </div>
                        </div>
                    ) : (
                        <div className="flex items-center justify-center p-4 rounded-xl bg-blue-50 dark:bg-blue-950/30 border border-blue-100 dark:border-blue-900/50 shadow-sm">
                            <p className="font-bold text-blue-700 dark:text-blue-400">
                                {t("programs.free")}
                            </p>
                        </div>
                    )}

                    {/* Payment Type */}
                    <div className="flex items-center gap-2">
                        <div className="h-px flex-1 bg-gray-200 dark:bg-zinc-800" />
                        <Badge className="bg-gradient-to-r from-primary-tw-100 to-purple-100 dark:from-primary-tw-950 dark:to-purple-950 text-primary-tw-700 dark:text-primary-tw-400 border border-primary-tw-200 dark:border-primary-tw-800 font-semibold px-4 py-2 shadow-sm">
                            {t(`checkout.${history?.type}.title`)}
                        </Badge>
                        <div className="h-px flex-1 bg-gray-200 dark:bg-zinc-800" />
                    </div>
                </div>
            </div>

            {/* Bottom gradient line */}
            <div className="h-1 bg-gradient-to-r from-primary-tw-500 via-purple-600 to-pink-500 opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
        </div>
    );
}
