import React, { useState, useEffect } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { toast } from 'sonner';
import UserLayout from '@/Layouts/UserLayout';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Separator } from "@/Components/ui/separator";
import { Checkbox } from "@/Components/ui/checkbox";
import { ShoppingCart, Trash2, Minus, Plus, Store, ArrowRight, ShieldCheck, Loader2 } from "lucide-react";
import CartCheckoutModal from '@/Components/CartCheckoutModal';
import { useTranslation } from '@/hooks/useTranslation';

export default function Cart({ cartItems, currencies, gateways, userCountryIso2, addresses }) { 
    const { activeCurrency } = usePage().props;
    const { t } = useTranslation();
    
    const currencySymbol = activeCurrency?.symbol || '$';
    const exchangeRate = parseFloat(activeCurrency?.exchange_rate || 1);

    const [localCartItems, setLocalCartItems] = useState(cartItems);
    const [selectedItems, setSelectedItems] = useState([]);
    const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
    const [isUpdating, setIsUpdating] = useState(null); 

    useEffect(() => {
        setLocalCartItems(cartItems);
    }, [cartItems]);

    const isAllSelected = localCartItems.length > 0 && selectedItems.length === localCartItems.length;

    const toggleAll = () => {
        if (isAllSelected) setSelectedItems([]);
        else setSelectedItems(localCartItems.map(i => i.id));
    };

    const toggleItem = (id) => {
        if (selectedItems.includes(id)) {
            setSelectedItems(selectedItems.filter(i => i !== id));
        } else {
            setSelectedItems([...selectedItems, id]);
        }
    };

    const updateQuantity = (cartId, newQuantity, minQty, maxQty) => {
        const qty = Number(newQuantity);
        const min = Number(minQty);
        const max = Number(maxQty);

        if (qty < min) {
            return toast.error(t('Minimum order quantity is :moq', { moq: min }));
        }
        if (qty > max) {
            return toast.error(t('Only :stock items available in stock.', { stock: max }));
        }

        setLocalCartItems(prev => prev.map(item => 
            item.id === cartId ? { ...item, quantity: qty } : item
        ));

        setIsUpdating(cartId);

        router.post(route('marketplace.cart.update', cartId), { 
            _method: 'PUT',
            quantity: qty 
        }, { 
            preserveScroll: true,
            preserveState: true,
            onFinish: () => setIsUpdating(null),
            onError: () => {
                setLocalCartItems(cartItems);
                toast.error(t('Failed to update quantity.'));
            }
        });
    };

    const removeItem = (cartId) => {
        setLocalCartItems(prev => prev.filter(i => i.id !== cartId));
        setSelectedItems(prev => prev.filter(i => i !== cartId));

        router.post(route('marketplace.cart.destroy', cartId), {
            _method: 'DELETE'
        }, {
            preserveScroll: true,
            preserveState: true,
            onSuccess: () => toast.success(t('Item removed from cart.')),
            onError: () => setLocalCartItems(cartItems) 
        });
    };

    const selectedCartObjects = localCartItems.filter(i => selectedItems.includes(i.id));
    
    const subtotal = selectedCartObjects.reduce((acc, item) => {
        const productRate = parseFloat(currencies?.find(c => c.code === (item.product.currency_code || 'USD'))?.exchange_rate || 1);
        let baseUsdPrice = parseFloat(item.product.original_price || item.product.price || 0) / productRate;
        
        Object.values(item.selected_variations || {}).forEach(opt => {
            if (opt && opt.additional_price) {
                baseUsdPrice += (parseFloat(opt.additional_price) / productRate);
            }
        });
        
        return acc + (baseUsdPrice * Number(item.quantity));
    }, 0) * exchangeRate;

    return (
        <UserLayout>
            <Head title={t('Shopping Cart')} />

            <CartCheckoutModal 
                isOpen={isCheckoutOpen} 
                onClose={() => setIsCheckoutOpen(false)} 
                selectedCartItems={selectedCartObjects} 
                gateways={gateways} 
                currencies={currencies}
                userCountryIso2={userCountryIso2} 
                addresses={addresses}
            />

            <div className="mb-6 flex items-center gap-3">
                <ShoppingCart className="w-8 h-8 text-primary" />
                <h1 className="text-2xl font-bold tracking-tight">{t('Your Cart')}</h1>
            </div>

            {localCartItems.length === 0 ? (
                <div className="flex flex-col items-center justify-center p-12 bg-card rounded-xl border border-dashed border-border text-center">
                    <div className="w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4">
                        <ShoppingCart className="w-12 h-12 text-muted-foreground opacity-50" />
                    </div>
                    <h2 className="text-2xl font-bold mb-2">{t('Your cart is empty')}</h2>
                    <p className="text-muted-foreground mb-6">{t("Looks like you haven't added anything to your cart yet.")}</p>
                    <Button asChild size="lg" className="rounded-full px-8">
                        <Link href="/">{t('Continue Shopping')}</Link>
                    </Button>
                </div>
            ) : (
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
                    
                    <div className="lg:col-span-2 space-y-4">
                        <Card className="border-border/50 shadow-sm">
                            <div className="px-4 py-3 flex items-center gap-3">
                                <Checkbox 
                                    checked={isAllSelected} 
                                    onCheckedChange={toggleAll} 
                                    id="selectAll" 
                                />
                                <label htmlFor="selectAll" className="text-sm font-bold cursor-pointer">
                                    {t('Select All Items (:count)', { count: localCartItems.length })}
                                </label>
                            </div>
                        </Card>

                        {localCartItems.map((item) => {
                            const mainImg = item.product.images?.find(img => img.is_main) || item.product.images?.[0];
                            const imgUrl = mainImg ? `/storage/${mainImg.path}` : '/placeholder.jpg';
                            const isSelected = selectedItems.includes(item.id);
                            
                            // Enforce number types for calculations
                            const currentQty = Number(item.quantity);
                            const maxStock = Number(item.product.stock);
                            const minMoq = Number(item.product.moq || 1);
                            
                            return (
                                <Card key={item.id} className={`overflow-hidden shadow-sm transition-all ${isSelected ? 'border-primary/50 bg-primary/5' : 'border-border/50'}`}>
                                    <div className="bg-muted/30 px-4 py-2 border-b flex items-center justify-between text-sm">
                                        <div className="flex items-center gap-2 font-semibold">
                                            <Store className="w-4 h-4 text-primary" />
                                            {item.product.seller?.company_name || item.product.seller?.name || t('Verified Supplier')}
                                        </div>
                                    </div>
                                    <CardContent className="p-4 flex flex-col sm:flex-row gap-4 sm:items-center relative">
                                        
                                        <Checkbox 
                                            checked={isSelected} 
                                            onCheckedChange={() => toggleItem(item.id)} 
                                            className="absolute top-4 left-4 z-10"
                                        />

                                        <Button 
                                            variant="ghost" size="icon" onClick={() => removeItem(item.id)}
                                            className="absolute top-2 right-2 text-muted-foreground hover:text-red-500 hover:bg-red-50"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </Button>

                                        <Link href={route('product.view', `${item.product.slug}_${item.product.id}`)} className="shrink-0 ml-6 sm:ml-8">
                                            <div className="w-24 h-24 border rounded-md bg-white p-1">
                                                <img src={imgUrl} alt={item.product.title} className="w-full h-full object-contain" />
                                            </div>
                                        </Link>
                                        
                                        <div className="flex-1 mt-2 sm:mt-0">
                                            <Link href={route('product.view', `${item.product.slug}_${item.product.id}`)} className="font-bold text-base line-clamp-2 hover:text-primary transition-colors pr-8">
                                                {item.product.title}
                                            </Link>

                                            {item.selected_variations && Object.keys(item.selected_variations).length > 0 && (
                                                <div className="mt-1 flex flex-wrap gap-1">
                                                    {Object.entries(item.selected_variations).map(([key, opt]) => (
                                                        <span key={key} className="text-[10px] bg-background border px-1.5 py-0.5 rounded text-muted-foreground font-medium">
                                                            {t(key)}: {opt.value}
                                                        </span>
                                                    ))}
                                                </div>
                                            )}

                                            <p className="text-xs text-muted-foreground mt-1 mb-3">
                                                {t('MOQ: :moq pieces', { moq: minMoq })}
                                            </p>
                                            
                                            <div className="flex items-center justify-between">
                                                <div className="flex items-center gap-1 border rounded-lg p-1 bg-background shadow-sm relative">
                                                    <Button 
                                                        variant="ghost" size="icon" className="h-7 w-7" 
                                                        onClick={() => updateQuantity(item.id, currentQty - 1, minMoq, maxStock)}
                                                        disabled={currentQty <= minMoq || isUpdating === item.id}
                                                    >
                                                        <Minus className="w-3 h-3" />
                                                    </Button>
                                                    
                                                    <span className="w-8 text-center font-bold text-sm">
                                                        {isUpdating === item.id ? <Loader2 className="w-3 h-3 animate-spin mx-auto text-primary" /> : currentQty}
                                                    </span>

                                                    <Button 
                                                        variant="ghost" size="icon" className="h-7 w-7" 
                                                        onClick={() => updateQuantity(item.id, currentQty + 1, minMoq, maxStock)} 
                                                        disabled={currentQty >= maxStock || isUpdating === item.id}
                                                    >
                                                        <Plus className="w-3 h-3" />
                                                    </Button>
                                                </div>
                                                <div className="text-right">
                                                    {(() => {
                                                        const pRate = parseFloat(currencies?.find(c => c.code === (item.product.currency_code || 'USD'))?.exchange_rate || 1);
                                                        let baseUsd = parseFloat(item.product.original_price || item.product.price || 0) / pRate;
                                                        
                                                        Object.values(item.selected_variations || {}).forEach(opt => {
                                                            if (opt && opt.additional_price) {
                                                                baseUsd += (parseFloat(opt.additional_price) / pRate);
                                                            }
                                                        });
                                                        
                                                        const itemFinalPrice = baseUsd * exchangeRate;
                                                        
                                                        return (
                                                            <>
                                                                <p className="font-bold text-lg text-orange-600">
                                                                    {currencySymbol}{(itemFinalPrice * currentQty).toFixed(2)}
                                                                </p>
                                                                <p className="text-[10px] text-muted-foreground">
                                                                    {currencySymbol}{itemFinalPrice.toFixed(2)} / {t('item')}
                                                                </p>
                                                            </>
                                                        );
                                                    })()}
                                                </div>
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            );
                        })}
                    </div>

                    <div className="lg:col-span-1 sticky top-24">
                        <Card className="shadow-lg border-primary/20">
                            <CardContent className="p-6">
                                <h3 className="font-bold text-lg mb-4">{t('Order Summary')}</h3>
                                
                                <div className="space-y-3 text-sm mb-6">
                                    <div className="flex justify-between text-muted-foreground">
                                        <span>{t('Selected Items (:count)', { count: selectedItems.length })}</span>
                                        <span className="font-mono">{currencySymbol}{subtotal.toFixed(2)}</span>
                                    </div>
                                    <div className="flex justify-between text-muted-foreground">
                                        <span>{t('Shipping & Discounts')}</span>
                                        <span>{t('Calculated at checkout')}</span>
                                    </div>
                                    <Separator />
                                    <div className="flex justify-between font-bold text-lg">
                                        <span>{t('Total')}</span>
                                        <span className="text-orange-600 font-mono">{currencySymbol}{subtotal.toFixed(2)}</span>
                                    </div>
                                </div>

                                <Button 
                                    size="lg" 
                                    className="w-full rounded-full text-base font-bold shadow-md bg-orange-500 hover:bg-orange-600 text-white group"
                                    onClick={() => setIsCheckoutOpen(true)}
                                    disabled={selectedItems.length === 0}
                                >
                                    {t('Proceed to Checkout')} <ArrowRight className="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" />
                                </Button>

                                {selectedItems.length === 0 && (
                                    <p className="text-xs text-center text-red-500 mt-2 font-medium">
                                        {t('Please select at least one item.')}
                                    </p>
                                )}

                                <div className="mt-6 flex items-center justify-center gap-2 text-xs text-muted-foreground font-medium">
                                    <ShieldCheck className="w-4 h-4 text-green-600" />
                                    {t('Safe and Secure Payments')}
                                </div>
                            </CardContent>
                        </Card>
                    </div>

                </div>
            )}
        </UserLayout>
    );
}