import React, { useRef, useState, useEffect } from 'react';
import { Link, usePage } from '@inertiajs/react';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Clock, ChevronRight, ChevronLeft, ShoppingBag } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

export default function SuperDealsSection({ superDeals }) {
    const { activeCurrency, currencies } = usePage().props;
    const { t } = useTranslation();

    const scrollRef = useRef(null);
    const [showLeft, setShowLeft] = useState(false);
    const [showRight, setShowRight] = useState(false);

    const checkScroll = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeft(scrollLeft > 0);
            setShowRight(Math.ceil(scrollLeft + clientWidth) < scrollWidth - 2);
        }
    };

    useEffect(() => {
        checkScroll();
        window.addEventListener('resize', checkScroll);
        return () => window.removeEventListener('resize', checkScroll);
    }, [superDeals]);

    const handleScroll = (direction) => {
        if (scrollRef.current) {
            const scrollAmount = 300; 
            scrollRef.current.scrollBy({
                left: direction === 'left' ? -scrollAmount : scrollAmount,
                behavior: 'smooth'
            });
        }
    };

    if (!superDeals || superDeals.length === 0) return null;

    const currencySymbol = activeCurrency?.symbol || '$';
    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;

    return (
        <div className="mb-10 relative group">
            {/* Heading Section */}
            <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-4">
                    <h3 className="text-xl md:text-2xl font-bold flex items-center gap-2">
                        <span className="bg-red-500 text-white p-1 rounded-md"><Clock className="w-5 h-5" /></span>
                        {t('Super Deals')}
                    </h3>
                </div>
                <Button variant="link" className="text-primary pr-0" asChild>
                    <Link href={route('deals.index')}>
                        {t('View All')} <ChevronRight className="w-4 h-4 ml-1"/>
                    </Link>
                </Button>
            </div>

            {/* Horizontal Slider */}
            <div className="relative">
                {showLeft && (
                    <button 
                        onClick={() => handleScroll('left')}
                        className="absolute -left-4 top-1/2 -translate-y-1/2 z-30 w-10 h-10 rounded-full bg-card border shadow-lg flex items-center justify-center hover:bg-muted transition-all text-primary"
                    >
                        <ChevronLeft className="w-6 h-6" />
                    </button>
                )}

                <div 
                    ref={scrollRef}
                    onScroll={checkScroll}
                    className="flex overflow-x-auto no-scrollbar gap-4 pb-4 scroll-smooth"
                >
                    {superDeals.map((deal) => {
                        const mainImg = deal.images?.find(img => img.is_main) || deal.images?.[0];
                        
                        const productRate = currencies?.find(c => c.code === (deal.currency_code || 'USD'))?.exchange_rate || 1;
                        const baseUsdPrice = parseFloat(deal.original_price || deal.price || 0) / parseFloat(productRate);
                        const activeDisplayPrice = baseUsdPrice * targetRate;
                        
                        // --- UPDATED MATH FOR GLOBAL FLASH SALE ---
                        const productDiscount = parseFloat(deal.discount_percentage) || 0;
                        const sellerDiscount = parseFloat(deal.seller?.flash_sale_percentage) || 0;
                        const discountPercent = Math.max(productDiscount, sellerDiscount);
                        // ------------------------------------------

                        const discountedPrice = activeDisplayPrice - (activeDisplayPrice * (discountPercent / 100));

                        return (
                            <Link key={deal.id} href={route('product.view', `${deal.slug}_${deal.id}`)} className="shrink-0">
                                <Card className="w-[180px] sm:w-[220px] border-border/50 shadow-sm hover:shadow-md transition-all cursor-pointer group bg-card h-full flex flex-col">
                                    <CardContent className="p-3 flex-1 flex flex-col">
                                        <div className="w-full h-[140px] sm:h-[180px] rounded-lg bg-white mb-3 flex items-center justify-center overflow-hidden border">
                                            {mainImg ? (
                                                <img 
                                                    src={`/storage/${mainImg.path}`} 
                                                    className="w-full h-full object-contain" 
                                                    alt={deal.title} 
                                                />
                                            ) : (
                                                <ShoppingBag className="w-10 h-10 text-muted-foreground/20" />
                                            )}
                                        </div>
                                        
                                        {/* TITLE */}
                                        <p className="text-sm font-normal text-muted-foreground group-hover:text-primary transition-colors truncate mb-1" title={deal.title}>
                                            {deal.title}
                                        </p>
                                        
                                        <div className="flex items-end gap-2 mb-2 mt-auto">
                                            <span className="text-red-500 font-bold text-lg">
                                                {currencySymbol}{discountedPrice.toFixed(2)}
                                            </span>
                                            <span className="text-muted-foreground text-xs line-through pb-0.5">
                                                {currencySymbol}{activeDisplayPrice.toFixed(2)}
                                            </span>
                                        </div>
                                        
                                        <div className="w-full bg-muted rounded-full h-4 mb-1 overflow-hidden relative">
                                            <div className="bg-red-500/20 absolute inset-0"></div>
                                            <div className="absolute inset-0 flex items-center justify-center text-[9px] font-bold text-red-700">
                                                {t(':percent% OFF', { percent: discountPercent })}
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            </Link>
                        );
                    })}
                </div>

                {showRight && (
                    <button 
                        onClick={() => handleScroll('right')}
                        className="absolute -right-4 top-1/2 -translate-y-1/2 z-30 w-10 h-10 rounded-full bg-card border shadow-lg flex items-center justify-center hover:bg-muted transition-all text-primary"
                    >
                        <ChevronRight className="w-6 h-6" />
                    </button>
                )}
            </div>
        </div>
    );
}