import React, { useState, useEffect } from 'react';
import { Head, Link } from '@inertiajs/react';
import axios from 'axios';
import UserLayout from '@/Layouts/UserLayout';
import ProductCard from '@/Components/ProductCard';
import { Button } from "@/Components/ui/button";
import { Tag, Loader2, ArrowDownCircle, PackageSearch } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

export default function SuperDeals({ initialProducts }) {
    const { t } = useTranslation();
    const [products, setProducts] = useState(initialProducts.data);
    const [nextPageUrl, setNextPageUrl] = useState(initialProducts.next_page_url);
    const [loading, setLoading] = useState(false);
    
    const maxDiscount = products.length > 0 
        ? Math.max(...products.map(p => parseFloat(p.discount_percentage || 0)))
        : 0;

    useEffect(() => {
        setProducts(initialProducts.data);
        setNextPageUrl(initialProducts.next_page_url);
    }, [initialProducts]);

    const handleLoadMore = async () => {
        if (!nextPageUrl) return;
        setLoading(true);
        try {
            const res = await axios.get(nextPageUrl, { 
                headers: { Accept: 'application/json' } 
            });
            setProducts(prev => [...prev, ...res.data.data]);
            setNextPageUrl(res.data.next_page_url);
        } catch (error) {
            console.error("Failed to load more deals", error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <UserLayout>
            <Head title={t('Super Deals & Discounts')} />

            <div className="mb-8 bg-gradient-to-r from-red-600 to-orange-500 rounded-3xl p-8 md:p-12 text-white shadow-lg flex flex-col md:flex-row items-center justify-between gap-6">
                <div>
                    <div className="flex items-center gap-3 mb-2">
                        <div className="p-2 bg-white/20 rounded-xl backdrop-blur-sm">
                            <Tag className="w-8 h-8 text-white" />
                        </div>
                        <h1 className="text-3xl md:text-5xl font-black tracking-tight">
                            {t('Super Deals')}
                        </h1>
                    </div>
                    <p className="text-red-100 text-base md:text-lg max-w-xl">
                        {t('Discover top-rated products with massive discounts. Hurry, these deals won\'t last forever!')}
                    </p>
                </div>
                
                {/* --- UPDATED: Dynamic Maximum Discount Badge --- */}
                {maxDiscount > 0 && (
                    <div className="bg-white/10 backdrop-blur-sm border border-white/20 p-4 rounded-2xl text-center shrink-0 min-w-[200px]">
                        <p className="text-sm font-bold text-red-100 uppercase tracking-widest mb-1">
                            {t('Up To')}
                        </p>
                        <p className="text-5xl font-black text-white">
                            {t(':percentage% OFF', { percentage: Math.round(maxDiscount) })}
                        </p>
                    </div>
                )}
            </div>

            {products.length === 0 ? (
                <div className="text-center py-24 bg-card border border-dashed rounded-3xl text-muted-foreground shadow-sm">
                    <PackageSearch className="w-16 h-16 mx-auto opacity-20 mb-4" />
                    <h3 className="font-bold text-xl mb-2 text-foreground">
                        {t('No active deals right now')}
                    </h3>
                    <p className="max-w-sm mx-auto text-sm mb-6">
                        {t('We currently don\'t have any products on sale. Check back later for amazing discounts!')}
                    </p>
                    <Button asChild variant="outline" className="rounded-full shadow-sm">
                        <Link href="/">{t('Browse All Products')}</Link>
                    </Button>
                </div>
            ) : (
                <>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 md:gap-6">
                        {products.map(product => (
                            <ProductCard key={product.id} product={product} />
                        ))}
                    </div>

                    {nextPageUrl && (
                        <div className="mt-12 text-center pb-8">
                            <Button 
                                variant="outline" 
                                size="lg"
                                onClick={handleLoadMore}
                                disabled={loading}
                                className="rounded-full px-12 font-bold shadow-sm bg-card hover:bg-muted gap-2 border-primary/20 hover:border-primary/50 transition-all text-primary"
                            >
                                {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <ArrowDownCircle className="w-5 h-5" />}
                                {loading ? t('Loading Deals...') : t('Load More Deals')}
                            </Button>
                        </div>
                    )}
                </>
            )}
        </UserLayout>
    );
}