import React, { useState, useEffect, useMemo } from 'react';
import { router, usePage } from '@inertiajs/react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { CreditCard, ShieldCheck, Loader2, XCircle, Info, FileText } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';

export default function OrderPayModal({ isOpen, onClose, order, gateways, userCountryIso2 }) {
    if (!order) return null;

    const { t } = useTranslation();
    const { currencies } = usePage().props;
    const [selectedGateway, setSelectedGateway] = useState(null);
    const [processing, setProcessing] = useState(false);

    // Filter gateways based on user's country and currency support
    const availableGateways = useMemo(() => {
        return gateways.filter(g => {
            const isCountryAllowed = g.is_global || (userCountryIso2 && g.allowed_countries?.includes(userCountryIso2));
            const supportsCurrency = g.supported_currencies?.includes(order.currency);
            return isCountryAllowed && supportsCurrency;
        });
    }, [gateways, userCountryIso2, order.currency]);

    // Auto-select the first available gateway
    useEffect(() => {
        if (isOpen && availableGateways.length > 0 && !selectedGateway) {
            setSelectedGateway(availableGateways[0]);
        }
    }, [isOpen, availableGateways]);

    const orderCurrencyObj = currencies?.find(c => c.code === order.currency);
    const currencySymbol = orderCurrencyObj?.symbol || order.currency;
    const totalAmount = parseFloat(order.total_amount).toFixed(2);

    const handlePayment = () => {
        if (!selectedGateway) return toast.error(t("Please select a payment method."));

        setProcessing(true);
        router.post(route('payment.pay.pending', order.id), {
            gateway: selectedGateway.code,
        }, {
            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: 
                - flex flex-col max-h-[95dvh] bounds the modal to the physical screen height.
            */}
            <DialogContent className="max-w-md sm:rounded-2xl 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('Pay Pending Order')}
                    </DialogTitle>
                </DialogHeader>

                {/* Middle Content is flex-1 and overflow-y-auto to scroll independently */}
                <div className="p-6 space-y-6 bg-background flex-1 overflow-y-auto min-h-0 custom-scrollbar">
                    
                    {/* ORDER SUMMARY */}
                    <div className="p-4 border border-border/50 rounded-xl bg-muted/5 flex items-center justify-between">
                        <div>
                            <p className="text-xs font-bold text-muted-foreground uppercase tracking-widest mb-1 flex items-center gap-1">
                                <FileText className="w-3 h-3" /> {t('Order ID')}
                            </p>
                            <p className="font-mono font-bold text-foreground">{order.order_number}</p>
                        </div>
                        <div className="text-right">
                            <p className="text-xs font-bold text-muted-foreground uppercase tracking-widest mb-1">{t('Total Due')}</p>
                            <p className="font-black text-2xl text-orange-600">{currencySymbol}{totalAmount}</p>
                        </div>
                    </div>

                    {/* GATEWAY SELECTION */}
                    {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 Payment Gateway Available')}</p>
                            <p className="text-xs mt-1">
                                {t('There are no gateways configured for your country or the currency (:currency) of this order.', { currency: order.currency })}
                            </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>

                            {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>

                {/* 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={handlePayment} 
                        disabled={processing || availableGateways.length === 0}
                    >
                        {processing ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : null}
                        {processing ? t('Processing...') : (selectedGateway?.code === 'manual' ? t('Submit') : t('Pay :symbol:amount', { symbol: currencySymbol, amount: totalAmount }))}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}