import React, { useState, useEffect } from 'react';
import { Head, useForm } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Badge } from "@/Components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Loader2, PlusCircle, CheckCircle, Trash2, Banknote, RefreshCw, KeyRound, AlertCircle, Power } from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal';

export default function CurrencyManager({ apiKey }) {
    // Custom Tab State (Replaces Shadcn Tabs)
    const [activeTab, setActiveTab] = useState('currencies');

    const [currencies, setCurrencies] = useState([]);
    const [loading, setLoading] = useState(true);
    const [syncing, setSyncing] = useState(false);

    // Create Modal
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [newCurrency, setNewCurrency] = useState({ name: '', code: '', symbol: '', exchange_rate: 1 });
    const [isCreating, setIsCreating] = useState(false);

    // Delete Modal
    const [deleteId, setDeleteId] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);

    // Form for API Key
    const { data: apiData, setData: setApiData, post: postApi, processing: savingApi } = useForm({
        exchangerate_api_key: apiKey || ''
    });

    useEffect(() => { fetchCurrencies(); }, []);

    const fetchCurrencies = async () => {
        try {
            const res = await axios.get('/cp/api/admin/currencies');
            setCurrencies(res.data);
        } catch (e) { toast.error("Failed to load currencies"); } 
        finally { setLoading(false); }
    };

    const handleCreate = async () => {
        if (!newCurrency.name || !newCurrency.code || !newCurrency.symbol) return toast.error("All fields required");
        setIsCreating(true);
        try {
            await axios.post('/cp/api/admin/currencies', newCurrency);
            toast.success("Currency added successfully");
            setIsCreateOpen(false);
            setNewCurrency({ name: '', code: '', symbol: '', exchange_rate: 1 });
            fetchCurrencies();
        } catch (e) { toast.error(e.response?.data?.message || "Failed to add currency"); } 
        finally { setIsCreating(false); }
    };

    const handleAction = async (id, action) => {
        // Show loading state for default change since it now triggers a live API sync
        if (action === 'default') {
            toast.loading("Setting default & updating live market rates...", { id: "sync-toast" });
        }

        try {
            const res = await axios.post(`/cp/api/admin/currencies/${id}/${action}`);
            
            if (action === 'default') {
                toast.success(res.data.message || "Updated successfully", { id: "sync-toast" });
            } else {
                toast.success("Updated successfully");
            }
            
            fetchCurrencies();
        } catch (e) { 
            toast.error(e.response?.data?.message || "Action failed", { id: "sync-toast" }); 
        }
    };

    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/cp/api/admin/currencies/${deleteId}`);
            toast.success("Currency deleted");
            fetchCurrencies();
        } catch (e) { toast.error(e.response?.data?.message || "Failed to delete"); } 
        finally { setIsDeleteOpen(false); setDeleteId(null); }
    };

    const handleSync = async () => {
        setSyncing(true);
        toast.loading("Fetching live rates...", { id: "manual-sync" });
        try {
            const res = await axios.post('/cp/api/admin/currencies/sync');
            toast.success(res.data.message, { id: "manual-sync" });
            fetchCurrencies();
        } catch (e) {
            toast.error(e.response?.data?.message || "Failed to sync rates", { id: "manual-sync" });
        } finally {
            setSyncing(false);
        }
    };

    const saveApiKey = (e) => {
        e.preventDefault();
        postApi(route('cp.settings.currencies.save-key'), {
            preserveScroll: true,
            onSuccess: () => toast.success("API Key saved successfully")
        });
    };

    return (
        <AdminLayout>
            <Head title="Currency Manager" />

            <ConfirmModal 
                open={isDeleteOpen} onOpenChange={setIsDeleteOpen} onConfirm={handleDelete}
                title="Delete Currency?" description="This cannot be undone." variant="destructive"
            />

            <div className="max-w-6xl mx-auto space-y-6">
                
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-2">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-primary/10 rounded-lg shrink-0">
                            <Banknote className="w-8 h-8 text-primary" />
                        </div>
                        <div>
                            <h2 className="text-2xl font-bold tracking-tight">Currency & Exchange Rates</h2>
                            <p className="text-muted-foreground text-sm">Manage supported currencies and live market rates.</p>
                        </div>
                    </div>
                </div>

                {/* SLEEK UNDERLINE SCROLLABLE TABS */}
                <div className="w-full border-b border-border/60 overflow-x-auto no-scrollbar bg-card rounded-t-xl px-2 pt-2">
                    <div className="flex w-max min-w-full space-x-6 px-4">
                        <button 
                            onClick={() => setActiveTab('currencies')} 
                            className={`py-3 px-2 text-sm font-bold border-b-2 transition-all ${activeTab === 'currencies' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
                        >
                            Available Currencies
                        </button>
                        <button 
                            onClick={() => setActiveTab('api')} 
                            className={`py-3 px-2 text-sm font-bold border-b-2 transition-all ${activeTab === 'api' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
                        >
                            API Integration
                        </button>
                    </div>
                </div>

                {/* TAB CONTENT AREA */}
                <div className="pt-2">
                    
                    {/* Currencies Tab */}
                    {activeTab === 'currencies' && (
                        <Card className="shadow-sm border-border/50 animate-in fade-in duration-300">
                            <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between border-b bg-muted/10 pb-4 gap-4">
                                <div>
                                    <CardTitle>Supported Currencies</CardTitle>
                                    <CardDescription className="mt-1">Set your base currency and supported options.</CardDescription>
                                </div>
                                <div className="flex flex-wrap gap-2 w-full sm:w-auto">
                                    <Button variant="secondary" className="flex-1 sm:flex-none" onClick={handleSync} disabled={syncing}>
                                        <RefreshCw className={`mr-2 h-4 w-4 ${syncing ? 'animate-spin' : ''}`} /> Sync Rates
                                    </Button>
                                    <Button className="flex-1 sm:flex-none" onClick={() => setIsCreateOpen(true)}>
                                        <PlusCircle className="mr-2 h-4 w-4"/> Add Currency
                                    </Button>
                                </div>
                            </CardHeader>
                            <CardContent className="p-0 overflow-x-auto">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead className="pl-6">Currency</TableHead>
                                            <TableHead>Code</TableHead>
                                            <TableHead>Rate (vs Base)</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead className="text-right pr-6">Actions</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {loading ? (
                                            <TableRow><TableCell colSpan={5} className="text-center py-8"><Loader2 className="animate-spin mx-auto text-muted-foreground"/></TableCell></TableRow>
                                        ) : currencies.map(c => (
                                            <TableRow key={c.id}>
                                                <TableCell className="font-medium pl-6">
                                                    <div className="flex items-center gap-2">
                                                        <span className="w-6 text-center font-bold text-muted-foreground bg-muted rounded border">{c.symbol}</span>
                                                        {c.name}
                                                    </div>
                                                </TableCell>
                                                <TableCell><Badge variant="outline" className="uppercase font-mono bg-background">{c.code}</Badge></TableCell>
                                                <TableCell className="font-mono font-medium">{c.exchange_rate ?? '0.0000'}</TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        {c.is_default && <Badge className="bg-green-600 border-none text-white">Default Base</Badge>}
                                                        {!c.is_active && <Badge variant="destructive">Inactive</Badge>}
                                                    </div>
                                                </TableCell>
                                                <TableCell className="text-right pr-6 space-x-2">
                                                    {!c.is_default && (
                                                        <>
                                                            <Button size="icon" variant="ghost" onClick={() => handleAction(c.id, 'default')} title="Set as Base (Auto-syncs rates)">
                                                                <CheckCircle className="h-4 w-4 text-green-600" />
                                                            </Button>
                                                            <Button size="icon" variant="ghost" onClick={() => handleAction(c.id, 'toggle')} title="Toggle Active">
                                                                <Power className={`h-4 w-4 ${c.is_active ? 'text-orange-500' : 'text-primary'}`} />
                                                            </Button>
                                                            <Button size="icon" variant="ghost" className="text-red-500 hover:text-red-600 hover:bg-red-50" onClick={() => { setDeleteId(c.id); setIsDeleteOpen(true); }}>
                                                                <Trash2 className="h-4 w-4" />
                                                            </Button>
                                                        </>
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </CardContent>
                        </Card>
                    )}

                    {/* API Settings Tab */}
                    {activeTab === 'api' && (
                        <Card className="max-w-2xl shadow-sm border-border/50 animate-in fade-in duration-300">
                            <form onSubmit={saveApiKey}>
                                <CardHeader className="border-b bg-muted/10 pb-4">
                                    <CardTitle className="flex items-center gap-2"><KeyRound className="w-5 h-5 text-primary"/> ExchangeRate-API Setup</CardTitle>
                                    <CardDescription>Get your free API key from <a href="https://www.exchangerate-api.com" target="_blank" rel="noreferrer" className="text-blue-500 font-bold hover:underline">exchangerate-api.com</a> to enable automatic rate updates.</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-4 pt-6">
                                    <div className="space-y-2">
                                        <Label className="font-bold">API Key Secret</Label>
                                        <Input type="password" value={apiData.exchangerate_api_key} onChange={e => setApiData('exchangerate_api_key', e.target.value)} placeholder="Enter your 24-character API key here..." className="bg-background font-mono" />
                                    </div>
                                    <div className="flex items-start gap-3 p-4 text-sm rounded-xl bg-blue-500/10 text-blue-700 border border-blue-500/20">
                                        <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                        <p>Once your API key is saved, Laravel Scheduler will automatically run <code>php artisan currency:sync</code> daily to keep your rates highly accurate across all cross-currency checkouts.</p>
                                    </div>
                                </CardContent>
                                <CardFooter className="border-t bg-muted/10 px-6 py-4 justify-end">
                                    <Button type="submit" disabled={savingApi} className="w-full sm:w-auto shadow-sm">
                                        {savingApi ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null} Save API Key
                                    </Button>
                                </CardFooter>
                            </form>
                        </Card>
                    )}
                </div>
            </div>

            {/* Create Dialog */}
            <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader><DialogTitle>Add New Currency</DialogTitle></DialogHeader>
                    <div className="grid grid-cols-2 gap-4 py-4">
                        <div className="col-span-2 space-y-2">
                            <Label>Currency Name <span className="text-red-500">*</span></Label>
                            <Input value={newCurrency.name} onChange={e => setNewCurrency({...newCurrency, name: e.target.value})} placeholder="e.g. Euro" required />
                        </div>
                        <div className="space-y-2">
                            <Label>ISO Code (3 Letters) <span className="text-red-500">*</span></Label>
                            <Input maxLength={3} className="uppercase font-mono bg-muted/50" value={newCurrency.code} onChange={e => setNewCurrency({...newCurrency, code: e.target.value.toUpperCase()})} placeholder="EUR" required />
                        </div>
                        <div className="space-y-2">
                            <Label>Symbol <span className="text-red-500">*</span></Label>
                            <Input value={newCurrency.symbol} onChange={e => setNewCurrency({...newCurrency, symbol: e.target.value})} placeholder="€" required />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsCreateOpen(false)}>Cancel</Button>
                        <Button onClick={handleCreate} disabled={isCreating}>
                            {isCreating ? <Loader2 className="w-4 h-4 mr-2 animate-spin"/> : null}
                            Add Currency
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AdminLayout>
    );
}