import React, { useState, useEffect, useMemo } from 'react';
import { router, Link, usePage } from '@inertiajs/react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { CreditCard, ShieldCheck, Loader2, Minus, Plus, Tag, CheckCircle2, XCircle, MapPin, Info } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';

export default function CheckoutModal({ isOpen, onClose, product, gateways, currencies, userCountryIso2, initialQuantity, addresses = [], selectedVariations = {} }) {
    if (!product) return null;

    const { activeCurrency } = usePage().props;
    const { t } = useTranslation();

    const [quantity, setQuantity] = useState(initialQuantity || product.moq || 1);
    const [selectedGateway, setSelectedGateway] = useState(null);
    const [selectedCurrency, setSelectedCurrency] = useState('');
    const [processing, setProcessing] = useState(false);
    
    const [inputCoupon, setInputCoupon] = useState('');
    const [isCouponApplied, setIsCouponApplied] = useState(false);

    const shippingAddresses = addresses.filter(a => a.type === 'shipping');
    const [selectedAddressId, setSelectedAddressId] = useState('');

    useEffect(() => {
        if (isOpen) {
            setQuantity(initialQuantity || product?.moq || 1);
            setInputCoupon('');
            setIsCouponApplied(false);
            
            if (shippingAddresses.length > 0 && !selectedAddressId) {
                const def = shippingAddresses.find(a => a.is_default);
                setSelectedAddressId(def ? def.id.toString() : shippingAddresses[0].id.toString());
            }
        }
    }, [isOpen, initialQuantity, product?.moq, shippingAddresses, selectedAddressId]);

    const availableGateways = useMemo(() => {
        return gateways.filter(g => {
            if (g.is_global) return true;
            if (!userCountryIso2) return false; 
            return g.allowed_countries?.includes(userCountryIso2);
        });
    }, [gateways, userCountryIso2]);

    useEffect(() => {
        if (isOpen && availableGateways.length > 0 && !selectedGateway) {
            const firstGateway = availableGateways[0];
            setSelectedGateway(firstGateway);
            
            if (firstGateway.supported_currencies?.includes(activeCurrency?.code)) {
                setSelectedCurrency(activeCurrency.code);
            } else if (firstGateway.supported_currencies?.length > 0) {
                setSelectedCurrency(firstGateway.supported_currencies[0]);
            }
        }
    }, [isOpen, availableGateways, activeCurrency]);

    useEffect(() => {
        if (selectedGateway && selectedGateway.supported_currencies?.length > 0) {
            if (!selectedGateway.supported_currencies.includes(selectedCurrency)) {
                setSelectedCurrency(selectedGateway.supported_currencies[0]);
            }
        }
    }, [selectedGateway, selectedCurrency]);

    // --- CROSS CURRENCY & VARIATION MATH ---
    const productRate = currencies?.find(c => c.code === (product.currency_code || 'USD'))?.exchange_rate || 1;
    let baseUsdPrice = parseFloat(product.original_price || product.price || 0) / parseFloat(productRate);

    // Add selected variations extra price (Convert from product's original currency to base USD)
    Object.values(selectedVariations).forEach(opt => {
        if (opt && opt.additional_price) {
            baseUsdPrice += (parseFloat(opt.additional_price) / parseFloat(productRate));
        }
    });

    const activeCurrencyObj = currencies.find(c => c.code === selectedCurrency);
    const exchangeRate = activeCurrencyObj ? parseFloat(activeCurrencyObj.exchange_rate) : 1;
    const currencySymbol = activeCurrencyObj?.symbol || '$';

    const subtotalUsd = baseUsdPrice * quantity;
    
    const minOrderOriginal = parseFloat(product.original_min_order_amount || product.min_order_amount_for_discount) || 0;
    const minOrderUsd = minOrderOriginal / productRate;
    const meetsMinOrder = subtotalUsd >= minOrderUsd;

    // --- UPDATED MATH FOR GLOBAL FLASH SALE ---
    const productDiscount = parseFloat(product.discount_percentage) || 0;
    const sellerDiscount = parseFloat(product.seller?.flash_sale_percentage) || 0;
    const discountPercent = Math.max(productDiscount, sellerDiscount);
    // ------------------------------------------

    const hasAutoDiscount = discountPercent > 0 && !product.coupon_code;
    const isDiscountActive = (hasAutoDiscount || (discountPercent > 0 && isCouponApplied)) && meetsMinOrder;
    
    let discountAmountUsd = 0;
    if (isDiscountActive) {
        const rawDiscountUsd = subtotalUsd * (discountPercent / 100);
        const maxCapOriginal = parseFloat(product.max_discount_percentage) || 0;
        const maxCapUsd = maxCapOriginal > 0 ? (maxCapOriginal / productRate) : 0;
        discountAmountUsd = maxCapUsd > 0 ? Math.min(rawDiscountUsd, maxCapUsd) : rawDiscountUsd;
    }

    const baseShippingRate = parseFloat(product.original_shipping_charge || product.shipping_charge) || 0;
    const shippingUsdRate = baseShippingRate / productRate;
    let shippingUsd = 0;
    
    if (!product.is_free_shipping) {
        shippingUsd = product.shipping_charge_type === 'per_item' 
            ? shippingUsdRate * quantity 
            : shippingUsdRate;
    }

    const finalTotalUsd = subtotalUsd - discountAmountUsd + shippingUsd;

    const convertedBasePrice = (baseUsdPrice * exchangeRate).toFixed(2);
    const convertedSubtotal = (subtotalUsd * exchangeRate).toFixed(2);
    const convertedDiscount = (discountAmountUsd * exchangeRate).toFixed(2);
    const convertedShipping = (shippingUsd * exchangeRate).toFixed(2);
    const finalConvertedTotal = (finalTotalUsd * exchangeRate).toFixed(2);

    // Dynamic Image specific to selected variation (if any)
    const variationImage = Object.values(selectedVariations).find(v => v?.image_path)?.image_path;
    const mainImg = variationImage || product.images?.[0]?.path;

    const applyCoupon = () => {
        if (!inputCoupon) return;
        if (inputCoupon.toUpperCase() === product.coupon_code?.toUpperCase()) {
            if (subtotalUsd < minOrderUsd) {
                const convertedMin = (minOrderUsd * exchangeRate).toFixed(2);
                toast.error(t(`Minimum spend of ${currencySymbol}${convertedMin} required for this coupon.`));
                setIsCouponApplied(false);
            } else {
                setIsCouponApplied(true);
                toast.success(t("Coupon applied successfully!"));
            }
        } else {
            setIsCouponApplied(false);
            toast.error(t("Invalid coupon code."));
        }
    };

    const isOutOfStock = quantity > product.stock || product.stock === 0;

    const handleCheckout = () => {
        if (shippingAddresses.length === 0 || !selectedAddressId) {
            return toast.error(t("Please add a shipping address to proceed."));
        }
        if (!selectedGateway || !selectedCurrency) {
            return toast.error(t("Please select a payment method and currency."));
        }
        if (isOutOfStock) {
            return toast.error(t("Insufficient stock to complete this order."));
        }

        setProcessing(true);
        router.post(route('payment.process'), {
            gateway: selectedGateway.code,
            currency: selectedCurrency,
            product_id: product.id,
            quantity: quantity,
            shipping_address_id: selectedAddressId, 
            coupon_code: isCouponApplied ? inputCoupon.toUpperCase() : null,
            variations: selectedVariations // <-- Send variations to backend processor
        }, {
            preserveScroll: true,
            onFinish: () => setProcessing(false),
            onError: (err) => toast.error(err.error || t("Payment initialization failed."))
        });
    };

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !processing && onClose(open)}>
            {/* 
                CORE FIX: 
                - max-h-[95dvh] limits modal to the physical screen height.
                - flex flex-col creates boundaries.
                - overflow-hidden ensures nothing spills out of the rounded modal.
            */}
            <DialogContent className="max-w-5xl lg:max-w-6xl p-0 overflow-hidden bg-card border-none shadow-2xl flex flex-col max-h-[95dvh] sm:max-h-[90vh]">
                
                {/* Header is shrunk and pinned to the top */}
                <DialogHeader className="p-6 pb-4 border-b bg-muted/10 shrink-0">
                    <DialogTitle className="text-xl flex items-center gap-2">
                        <CreditCard className="w-5 h-5 text-primary" /> {t('Secure Checkout')}
                    </DialogTitle>
                </DialogHeader>

                {/* Middle Content is flex-1 and overflow-y-auto to scroll independently */}
                <div className="grid grid-cols-1 md:grid-cols-2 flex-1 overflow-y-auto min-h-0 custom-scrollbar">
                    
                    <div className="p-6 border-b md:border-b-0 md:border-r border-border/50 bg-muted/5 space-y-6">
                        
                        <div className="space-y-3">
                            <Label className="font-bold text-sm uppercase tracking-wider text-muted-foreground flex items-center gap-2">
                                <MapPin className="w-4 h-4" /> {t('Shipping Address')}
                            </Label>
                            {shippingAddresses.length === 0 ? (
                                <div className="bg-red-500/10 border border-red-500/20 p-4 rounded-xl text-center">
                                    <MapPin className="w-6 h-6 text-red-500 mx-auto mb-2 opacity-50" />
                                    <p className="text-sm font-bold text-red-600 mb-3">{t('No Shipping Address Found')}</p>
                                    <Button asChild size="sm" variant="outline" className="border-red-500/50 text-red-600 hover:bg-red-500/20">
                                        <Link href={route('buyer.addresses.index')}>{t('Add Address Book')}</Link>
                                    </Button>
                                </div>
                            ) : (
                                <Select value={selectedAddressId} onValueChange={setSelectedAddressId}>
                                    <SelectTrigger className="w-full h-auto py-3 bg-background shadow-sm items-start text-left">
                                        <SelectValue placeholder={t('Select an address')} />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {shippingAddresses.map(addr => (
                                            <SelectItem key={addr.id} value={addr.id.toString()} className="py-2">
                                                <div className="font-bold">{addr.contact_name} ({addr.contact_phone})</div>
                                                <div className="text-xs text-muted-foreground mt-0.5 truncate max-w-[280px]">
                                                    {addr.address_line_1}, {addr.city?.name ? addr.city.name+', ' : ''}{addr.country?.name}
                                                </div>
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            )}
                        </div>

                        <div>
                            <h3 className="font-bold text-sm uppercase tracking-wider text-muted-foreground mb-3">{t('Order Summary')}</h3>
                            <div className="flex gap-3 p-3 rounded-xl border bg-background shadow-sm">
                                <div className="w-16 h-16 rounded-lg border bg-white overflow-hidden shrink-0">
                                    {mainImg ? (
                                        <img src={`/storage/${mainImg}`} alt={product.title} className="w-full h-full object-contain" />
                                    ) : (
                                        <div className="w-full h-full bg-muted flex items-center justify-center text-xs text-muted-foreground">{t('No image')}</div>
                                    )}
                                </div>
                                <div className="flex-1">
                                    <p className="text-sm font-bold line-clamp-2 leading-tight">{product.title}</p>
                                    
                                    {/* Display Selected Variations */}
                                    {Object.keys(selectedVariations).length > 0 && (
                                        <div className="mt-1 flex flex-wrap gap-1">
                                            {Object.entries(selectedVariations).map(([key, opt]) => (
                                                <span key={key} className="text-[10px] bg-muted px-1.5 py-0.5 rounded text-muted-foreground font-medium">
                                                    {t(key)}: {opt.value}
                                                </span>
                                            ))}
                                        </div>
                                    )}

                                    <p className="text-xs text-primary font-mono mt-1">{t('Unit Price')}: {currencySymbol}{convertedBasePrice}</p>
                                </div>
                            </div>
                        </div>

                        <div className="space-y-3">
                            <div className="flex items-center justify-between">
                                <Label className="font-bold">{t('Quantity (MOQ: :moq)', { moq: product.moq })}</Label>
                                <span className="text-xs font-bold text-muted-foreground">{t(':stock Available', { stock: product.stock })}</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <Button variant="outline" size="icon" className="rounded-full" onClick={() => {
                                    setQuantity(Math.max(product.moq, quantity - 1));
                                    setIsCouponApplied(false);
                                }} disabled={quantity <= product.moq}><Minus className="w-4 h-4"/></Button>
                                <Input type="number" value={quantity} readOnly className="w-20 text-center font-bold text-lg bg-background rounded-xl focus-visible:ring-0 border-none shadow-sm" />
                                <Button variant="outline" size="icon" className="rounded-full" onClick={() => {
                                    setQuantity(Math.min(product.stock, quantity + 1));
                                    setIsCouponApplied(false); 
                                }} disabled={quantity >= product.stock}><Plus className="w-4 h-4"/></Button>
                            </div>
                            {isOutOfStock && (
                                <p className="text-xs text-red-600 font-bold flex items-center gap-1 mt-1">
                                    <XCircle className="w-3 h-3" /> {t('Requested quantity exceeds available stock.')}
                                </p>
                            )}
                        </div>

                        {product.coupon_code && !hasAutoDiscount && (
                            <div className="space-y-2 pt-2 border-t">
                                <Label className="font-bold text-xs uppercase tracking-wider text-muted-foreground flex items-center gap-1"><Tag className="w-3 h-3"/> {t('Have a Coupon?')}</Label>
                                {minOrderUsd > 0 && (
                                    <p className="text-[10px] text-muted-foreground">{t('Min. spend required:')} {currencySymbol}{(minOrderUsd * exchangeRate).toFixed(2)}</p>
                                )}
                                <div className="flex gap-2">
                                    <Input 
                                        placeholder={t('Enter code')} value={inputCoupon} onChange={e => setInputCoupon(e.target.value)}
                                        disabled={isCouponApplied} className="uppercase font-mono bg-background"
                                    />
                                    <Button variant={isCouponApplied ? "default" : "secondary"} onClick={isCouponApplied ? () => {setIsCouponApplied(false); setInputCoupon('');} : applyCoupon} className={isCouponApplied ? "bg-green-600 text-white" : ""}>
                                        {isCouponApplied ? <CheckCircle2 className="w-4 h-4" /> : t('Apply')}
                                    </Button>
                                </div>
                            </div>
                        )}

                        <div className="border-t border-dashed pt-4 mt-auto space-y-2">
                            <div className="flex justify-between text-muted-foreground text-sm">
                                <span>{t('Subtotal (:quantity items)', { quantity })}</span>
                                <span className="font-mono">{currencySymbol}{convertedSubtotal}</span>
                            </div>
                            {discountAmountUsd > 0 && (
                                <div className="flex justify-between text-green-600 text-sm font-medium">
                                    <span>{t('Discount')}</span>
                                    <span className="font-mono">-{currencySymbol}{convertedDiscount}</span>
                                </div>
                            )}
                            <div className="flex justify-between text-sm text-muted-foreground">
                                <span>{t('Shipping Fee')} {product.shipping_charge_type === 'per_item' ? `(${quantity}x)` : ''}</span>
                                <span className="font-mono">
                                    {shippingUsd === 0 ? <span className="text-green-600 font-bold">{t('Free')}</span> : `+${currencySymbol}${convertedShipping}`}
                                </span>
                            </div>
                            <div className="flex justify-between font-black text-2xl text-primary pt-2 border-t">
                                <span>{t('Total')}</span>
                                <span>{currencySymbol}{finalConvertedTotal}</span>
                            </div>
                        </div>
                    </div>

                    <div className="p-6 space-y-6 bg-background">
                        {availableGateways.length === 0 ? (
                            <div className="text-center p-6 bg-red-500/5 text-red-600 rounded-xl border border-red-500/20">
                                <XCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
                                <p className="font-bold">{t('No Gateway Available')}</p>
                                <p className="text-xs mt-1">{t('Check your regional settings.')}</p>
                            </div>
                        ) : (
                            <>
                                <div className="space-y-3">
                                    <h3 className="font-bold text-sm uppercase tracking-wider text-muted-foreground">{t('Select Payment Method')}</h3>
                                    <div className="grid gap-3">
                                        {availableGateways.map(g => (
                                            <div 
                                                key={g.code} onClick={() => setSelectedGateway(g)}
                                                className={`p-4 border-2 rounded-2xl cursor-pointer transition-all flex items-center justify-between group ${selectedGateway?.code === g.code ? 'border-primary bg-primary/5 shadow-md' : 'border-transparent bg-muted/30 hover:bg-muted/60'}`}
                                            >
                                                <span className={`font-bold text-sm ${selectedGateway?.code === g.code ? 'text-primary' : 'text-foreground'}`}>{g.name}</span>
                                                <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors ${selectedGateway?.code === g.code ? 'border-primary bg-primary' : 'border-muted-foreground group-hover:border-primary'}`}>
                                                    {selectedGateway?.code === g.code && <div className="w-2 h-2 bg-white rounded-full" />}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                {selectedGateway && (
                                    <div className="space-y-3 pt-4 border-t">
                                        <Label className="font-bold">{t('Select Currency')}</Label>
                                        <Select value={selectedCurrency} onValueChange={setSelectedCurrency}>
                                            <SelectTrigger className="w-full h-12 rounded-xl bg-muted/20 border-none shadow-sm">
                                                <SelectValue placeholder={t('Choose Currency')} />
                                            </SelectTrigger>
                                            <SelectContent className="rounded-xl">
                                                {selectedGateway.supported_currencies?.map(code => {
                                                    const cur = currencies.find(c => c.code === code);
                                                    return (
                                                        <SelectItem key={code} value={code} className="font-medium">
                                                            {code} {cur ? `(${cur.symbol})` : ''}
                                                        </SelectItem>
                                                    );
                                                })}
                                            </SelectContent>
                                        </Select>

                                        {selectedGateway.code === 'manual' && selectedGateway.instructions && (
                                            <div className="mt-4 p-4 border border-blue-500/20 bg-blue-500/10 rounded-xl text-sm leading-relaxed text-blue-900 dark:text-blue-100 flex gap-3 items-start animate-in fade-in slide-in-from-top-2">
                                                <Info className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
                                                <div className="whitespace-pre-wrap flex-1">
                                                    <span className="font-bold text-blue-700 dark:text-blue-400 block mb-1">{t('Payment Instructions')}:</span>
                                                    {selectedGateway.instructions}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </div>

                {/* Footer is shrunk and pinned to the bottom */}
                <DialogFooter className="p-4 sm:p-6 border-t bg-muted/10 flex flex-col sm:flex-row sm:justify-between items-center shrink-0 gap-4">
                    <div className="flex items-center text-xs uppercase tracking-widest font-bold text-muted-foreground gap-2">
                        <ShieldCheck className="w-5 h-5 text-green-600" /> {t('Secure Payment')}
                    </div>
                    <Button 
                        size="lg" 
                        className="w-full sm:w-auto px-12 rounded-full font-black text-lg shadow-xl active:scale-95 transition-transform" 
                        onClick={handleCheckout} 
                        disabled={processing || availableGateways.length === 0 || !selectedCurrency || shippingAddresses.length === 0 || !selectedAddressId || isOutOfStock}
                    >
                        {processing ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : null}
                        {processing 
                            ? t('Processing...') 
                            : (selectedGateway?.code === 'manual' 
                                ? t('Place Order') 
                                : t('Pay :symbol:amount', { symbol: currencySymbol, amount: finalConvertedTotal }))
                        }
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}