import React, { useEffect, useState } from 'react';
import { useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea"; // <-- NEW: Imported Textarea
import { Label } from "@/Components/ui/label";
import { Switch } from "@/Components/ui/switch";
import { ScrollArea } from "@/Components/ui/scroll-area";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Badge } from "@/Components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/Components/ui/tooltip";
import { Loader2, CheckCircle2, ShieldAlert, Settings, Globe, AlertCircle, X } from 'lucide-react';

export default function ConfigModal({ isOpen, onClose, gateway, currencies, countries }) {
    const [countrySearch, setCountrySearch] = useState('');
    const [currencyToAdd, setCurrencyToAdd] = useState('');

    const { data, setData, put, processing } = useForm({
        is_active: false,
        mode: 'sandbox',
        is_global: true,
        allowed_countries: [],
        supported_currencies: [],
        test_credentials: {},
        live_credentials: {}
    });

    useEffect(() => {
        if (gateway) {
            setData({
                is_active: gateway.is_active,
                mode: gateway.mode,
                is_global: gateway.is_global ?? true,
                allowed_countries: gateway.allowed_countries || [],
                supported_currencies: gateway.supported_currencies || [],
                test_credentials: gateway.test_credentials || {},
                live_credentials: gateway.live_credentials || {}
            });
            setCountrySearch(''); 
            setCurrencyToAdd(''); // Reset selection on open
        }
    }, [gateway, isOpen]);

    if (!gateway) return null;

    const handleCredentialChange = (env, key, value) => {
        setData(env, { ...data[env], [key]: value });
    };

    const toggleCountry = (iso2) => {
        const current = data.allowed_countries;
        const updated = current.includes(iso2) 
            ? current.filter(c => c !== iso2) 
            : [...current, iso2];
        setData('allowed_countries', updated);
    };

    const addCurrency = () => {
        if (currencyToAdd && !data.supported_currencies.includes(currencyToAdd)) {
            setData('supported_currencies', [...data.supported_currencies, currencyToAdd]);
            setCurrencyToAdd(''); // reset select after adding
        }
    };

    const removeCurrency = (code) => {
        setData('supported_currencies', data.supported_currencies.filter(c => c !== code));
    };

    const filteredCountries = countries.filter(c => 
        c.name.toLowerCase().includes(countrySearch.toLowerCase()) || 
        c.iso2.toLowerCase().includes(countrySearch.toLowerCase())
    );

    const saveConfig = (e) => {
        e.preventDefault();
        put(route('cp.settings.payments.update', gateway.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(`${gateway.name} updated successfully`);
                onClose();
            },
            onError: () => toast.error("Failed to update gateway.")
        });
    };

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="max-w-2xl max-h-[90vh] flex flex-col p-0">
                <form onSubmit={saveConfig} className="flex flex-col h-full overflow-hidden">
                    
                    {/* STICKY HEADER */}
                    <DialogHeader className="p-6 pb-2 border-b shrink-0">
                        <DialogTitle className="flex items-center gap-2 text-xl">
                            Configure {gateway.name}
                        </DialogTitle>
                    </DialogHeader>

                    {/* SCROLLABLE CONTENT AREA */}
                    <div className="flex-1 overflow-y-auto p-6">
                        <div className="space-y-8">
                            
                            {/* Status & Mode */}
                            <div className="flex flex-col sm:flex-row gap-6 bg-muted/30 p-4 rounded-xl border">
                                <div className="space-y-1 flex-1">
                                    <Label>Gateway Status</Label>
                                    <div className="flex items-center gap-2 mt-2">
                                        <Switch 
                                            checked={data.is_active} 
                                            onCheckedChange={(val) => setData('is_active', val)} 
                                            className="data-[state=checked]:bg-green-600 data-[state=unchecked]:bg-gray-300 dark:data-[state=unchecked]:bg-gray-700"
                                        />
                                        <span className="text-sm font-medium">{data.is_active ? 'Active' : 'Disabled'}</span>
                                    </div>
                                </div>
                                <div className="space-y-1 flex-1">
                                    <Label>Operation Mode</Label>
                                    <div className="flex items-center gap-2 mt-2">
                                        <Switch 
                                            checked={data.mode === 'live'} 
                                            onCheckedChange={(val) => setData('mode', val ? 'live' : 'sandbox')} 
                                            className="data-[state=checked]:bg-green-600 data-[state=unchecked]:bg-orange-500"
                                        />
                                        <span className={`text-sm font-bold ${data.mode === 'live' ? 'text-green-600' : 'text-orange-500'}`}>
                                            {data.mode === 'live' ? 'Live Production' : 'Sandbox Testing'}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            {/* --- Country Availability Settings --- */}
                            <div className="space-y-4">
                                <div>
                                    <Label className="text-lg font-semibold">Country Availability</Label>
                                    <p className="text-sm text-muted-foreground">Select where this gateway can be used by buyers.</p>
                                </div>

                                <div className="flex items-center gap-3 p-3 border rounded-lg bg-background">
                                    <Switch 
                                        checked={data.is_global} 
                                        onCheckedChange={(val) => setData('is_global', val)} 
                                        className="data-[state=checked]:bg-blue-600 data-[state=unchecked]:bg-gray-300 dark:data-[state=unchecked]:bg-gray-700"
                                    />
                                    <div>
                                        <Label className="cursor-pointer text-base">Available Globally (Worldwide)</Label>
                                        <p className="text-xs text-muted-foreground">Allows buyers from any country to use this gateway.</p>
                                    </div>
                                </div>

                                {!data.is_global && (
                                    <div className="border rounded-xl p-4 bg-muted/10 space-y-3">
                                        <div className="flex items-center justify-between">
                                            <Label>Select Specific Countries</Label>
                                            <span className="text-xs font-bold text-primary bg-primary/10 px-2 py-1 rounded">
                                                {data.allowed_countries.length} Selected
                                            </span>
                                        </div>
                                        <Input 
                                            placeholder="Search countries..." 
                                            value={countrySearch}
                                            onChange={(e) => setCountrySearch(e.target.value)}
                                            className="bg-background"
                                        />
                                        <ScrollArea className="h-48 border rounded-md p-1 bg-background">
                                            {filteredCountries.map(c => {
                                                const isSelected = data.allowed_countries.includes(c.iso2);
                                                return (
                                                    <div 
                                                        key={c.iso2} 
                                                        className={`flex items-center justify-between p-2 rounded-md cursor-pointer transition-colors ${isSelected ? 'bg-primary/10' : 'hover:bg-muted'}`}
                                                        onClick={() => toggleCountry(c.iso2)}
                                                    >
                                                        <div className="flex items-center gap-3">
                                                            <div className={`w-4 h-4 rounded border flex items-center justify-center ${isSelected ? 'bg-primary border-primary' : 'border-input bg-background'}`}>
                                                                {isSelected && <CheckCircle2 className="w-3 h-3 text-primary-foreground" />}
                                                            </div>
                                                            <span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
                                                                {c.name}
                                                            </span>
                                                        </div>
                                                        <span className="text-xs text-muted-foreground font-mono">{c.iso2}</span>
                                                    </div>
                                                );
                                            })}
                                            {filteredCountries.length === 0 && (
                                                <div className="p-4 text-center text-sm text-muted-foreground">No countries found.</div>
                                            )}
                                        </ScrollArea>
                                    </div>
                                )}
                            </div>

                            {/* --- Currency Mapping with Manual Add & Tooltip --- */}
                            <div className="space-y-3 p-4 border rounded-xl bg-orange-500/5 border-orange-500/20">
                                <div className="flex items-center gap-2">
                                    <Label className="text-lg font-semibold text-orange-700 dark:text-orange-500">Currency Mapping</Label>
                                    <TooltipProvider>
                                        <Tooltip delayDuration={100}>
                                            <TooltipTrigger asChild>
                                                <AlertCircle className="w-5 h-5 text-orange-600 cursor-help" />
                                            </TooltipTrigger>
                                            <TooltipContent 
                                                side="top" 
                                                className="max-w-xs border-orange-500/30 bg-white dark:bg-zinc-950 text-slate-900 dark:text-zinc-100 shadow-2xl p-3 z-[9999]"
                                            >
                                                <p className="text-sm">
                                                    <strong className="text-orange-600 dark:text-orange-400">Warning:</strong> You must confirm that the gateway officially accepts the currency you add here. Adding an unsupported currency will cause checkout errors for buyers!
                                                </p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                </div>
                                <p className="text-sm text-muted-foreground">Manually add available currencies that {gateway.name} supports.</p>
                                
                                <div className="flex flex-col sm:flex-row items-center gap-2">
                                    <Select value={currencyToAdd} onValueChange={setCurrencyToAdd}>
                                        <SelectTrigger className="w-full sm:w-[250px] bg-background">
                                            <SelectValue placeholder="Select available currency" />
                                        </SelectTrigger>
                                        <SelectContent className="z-[9999]">
                                            {currencies.filter(c => !data.supported_currencies.includes(c.code)).map(c => (
                                                <SelectItem key={c.code} value={c.code}>
                                                    {c.code} ({c.symbol})
                                                </SelectItem>
                                            ))}
                                            {currencies.filter(c => !data.supported_currencies.includes(c.code)).length === 0 && (
                                                <SelectItem value="none" disabled>All available currencies added</SelectItem>
                                            )}
                                        </SelectContent>
                                    </Select>
                                    <Button type="button" variant="secondary" onClick={addCurrency} disabled={!currencyToAdd} className="w-full sm:w-auto">
                                        Add Currency
                                    </Button>
                                </div>

                                <div className="flex flex-wrap gap-2 pt-3">
                                    {data.supported_currencies.map(code => {
                                        const cur = currencies.find(c => c.code === code);
                                        return (
                                            <Badge key={code} className="px-3 py-1.5 text-sm flex items-center gap-2 bg-background border shadow-sm text-foreground hover:bg-muted transition-colors">
                                                <span className="font-bold text-primary">{code}</span> {cur ? `(${cur.symbol})` : ''}
                                                <button type="button" onClick={() => removeCurrency(code)} className="text-muted-foreground hover:text-destructive ml-1 transition-colors">
                                                    <X className="w-4 h-4" />
                                                </button>
                                            </Badge>
                                        );
                                    })}
                                    {data.supported_currencies.length === 0 && (
                                        <span className="text-sm text-muted-foreground italic px-1">No currencies mapped yet.</span>
                                    )}
                                </div>
                            </div>

                            {/* Credentials - UPDATED WITH TEXTAREA FOR LONG TEXT */}
                            <div className="space-y-4">
                                <Label className="text-lg font-semibold flex items-center gap-2">
                                    {data.mode === 'live' ? <ShieldAlert className="w-5 h-5 text-green-600"/> : <Settings className="w-5 h-5 text-orange-500"/>}
                                    {data.mode === 'live' ? 'Live API Credentials' : 'Test API Credentials'}
                                </Label>
                                
                                <div className="grid gap-4 bg-muted/10 p-5 rounded-xl border">
                                    {Object.keys(data.mode === 'live' ? data.live_credentials : data.test_credentials).map(key => {
                                        const isSecret = ['secret', 'token', 'password', 'key', 'sid'].some(term => key.toLowerCase().includes(term));
                                        const isLongText = ['instruction', 'message', 'note'].some(term => key.toLowerCase().includes(term));

                                        return (
                                            <div key={key} className="space-y-1.5">
                                                <Label className="capitalize">{key.replace(/_/g, ' ')}</Label>
                                                
                                                {isLongText ? (
                                                    <Textarea 
                                                        value={data.mode === 'live' ? data.live_credentials[key] : data.test_credentials[key]}
                                                        onChange={(e) => handleCredentialChange(data.mode === 'live' ? 'live_credentials' : 'test_credentials', key, e.target.value)}
                                                        placeholder={`Enter ${key.replace(/_/g, ' ')}`}
                                                        className="bg-background min-h-[100px] resize-y"
                                                    />
                                                ) : (
                                                    <Input 
                                                        type={isSecret ? 'password' : 'text'}
                                                        value={data.mode === 'live' ? data.live_credentials[key] : data.test_credentials[key]}
                                                        onChange={(e) => handleCredentialChange(data.mode === 'live' ? 'live_credentials' : 'test_credentials', key, e.target.value)}
                                                        placeholder={`Enter ${key.replace(/_/g, ' ')}`}
                                                        className="bg-background"
                                                    />
                                                )}
                                            </div>
                                        );
                                    })}
                                    {Object.keys(data.mode === 'live' ? data.live_credentials : data.test_credentials).length === 0 && (
                                        <p className="text-sm text-muted-foreground italic py-2">No credentials required.</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* STICKY FOOTER */}
                    <DialogFooter className="p-4 border-t bg-muted/10 shrink-0">
                        <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
                        <Button type="submit" disabled={processing}>
                            {processing && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Save Configuration
                        </Button>
                    </DialogFooter>

                </form>
            </DialogContent>
        </Dialog>
    );
}