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

export default function AiProviders() {
    const [providers, setProviders] = useState([]);
    const [autoSelect, setAutoSelect] = useState(false);
    const [loading, setLoading] = useState(true);
    const [isSavingGlobal, setIsSavingGlobal] = useState(false);
    
    // Modals
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSavingModal, setIsSavingModal] = useState(false);
    const [editingProvider, setEditingProvider] = useState(null);
    const [deleteId, setDeleteId] = useState(null);

    const [formData, setFormData] = useState({
        provider_key: '',
        provider_name: '',
        api_endpoint: '',
        api_key: '',
        default_model: '',
        notes: '',
        priority: 99,
        is_enabled: true,
    });

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

    const fetchData = async () => {
        setLoading(true);
        try {
            const res = await axios.get('/cp/api/admin/ai-providers');
            setAutoSelect(res.data.settings.ai_auto_select_enabled);
            setProviders(res.data.providers);
        } catch (e) {
            toast.error("Failed to load AI configurations.");
        } finally {
            setLoading(false);
        }
    };

    const handleSaveGlobal = async () => {
        setIsSavingGlobal(true);
        try {
            await axios.post('/cp/api/admin/settings/ai', { ai_auto_select_enabled: autoSelect });
            toast.success("Global Auto-Fallback setting updated.");
        } catch (e) { 
            toast.error("Failed to save global settings."); 
        } finally { 
            setIsSavingGlobal(false); 
        }
    };

    const openModal = (provider = null) => {
        if (provider) {
            setEditingProvider(provider);
            setFormData({
                provider_key: provider.provider_key,
                provider_name: provider.provider_name,
                api_endpoint: provider.api_endpoint,
                api_key: '', // Keep blank for security
                default_model: provider.default_model,
                notes: provider.notes || '',
                priority: provider.priority,
                is_enabled: provider.is_enabled,
            });
        } else {
            setEditingProvider(null);
            setFormData({
                provider_key: '', provider_name: '', api_endpoint: '', api_key: '',
                default_model: '', notes: '', priority: 99, is_enabled: true,
            });
        }
        setIsModalOpen(true);
    };

    const handleModalSubmit = async (e) => {
        e.preventDefault();
        setIsSavingModal(true);
        const url = editingProvider ? `/cp/api/admin/ai-providers/${editingProvider.id}` : '/cp/api/admin/ai-providers';
        const method = editingProvider ? 'put' : 'post';

        try {
            const res = await axios[method](url, formData);
            toast.success(res.data.message);
            setIsModalOpen(false);
            fetchData();
        } catch (error) {
            toast.error(error.response?.data?.message || "Operation failed.");
        } finally {
            setIsSavingModal(false);
        }
    };

    const handleSetActive = async (id) => {
        toast.loading("Updating defaults...", { id: "default-toast" });
        try {
            const res = await axios.post(`/cp/api/admin/ai-providers/${id}/set-active`);
            toast.success(res.data.message, { id: "default-toast" });
            fetchData();
        } catch (error) {
            toast.error(error.response?.data?.message || "Failed to activate.", { id: "default-toast" });
        }
    };
    
    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            const res = await axios.delete(`/cp/api/admin/ai-providers/${deleteId}`);
            toast.success(res.data.message);
            fetchData();
        } catch (error) {
            toast.error(error.response?.data?.message || "Deletion failed.");
        } finally {
            setDeleteId(null);
        }
    };

    return (
        <AdminLayout>
            <Head title="AI System Providers" />
            
            <ConfirmModal 
                open={!!deleteId} 
                onOpenChange={(val) => !val && setDeleteId(null)}
                onConfirm={handleDelete}
                title="Delete AI Provider?"
                description="This action cannot be undone. You will lose the API key and configurations for this provider."
                variant="destructive"
            />

            <div className="max-w-6xl mx-auto space-y-6 pb-12">
                <div className="flex items-center gap-3 mb-6">
                    <BrainCircuit className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">AI Generation Engine</h2>
                        <p className="text-muted-foreground">Manage API keys and fail-over priorities for AI-powered features.</p>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    
                    {/* --- Global Settings Panel --- */}
                    <div className="lg:col-span-1 space-y-6">
                        <Card className="shadow-sm border-border/50">
                            <CardHeader className="bg-muted/10 border-b pb-4">
                                <CardTitle className="text-lg">Smart Auto-Fallback</CardTitle>
                                <CardDescription>Highly recommended for production.</CardDescription>
                            </CardHeader>
                            <CardContent className="pt-6">
                                <div className="flex items-start gap-4 p-4 border rounded-xl bg-card">
                                    <Switch checked={autoSelect} onCheckedChange={setAutoSelect} className="mt-1" />
                                    <div>
                                        <Label className="font-bold text-base">Enable Auto-Fallback</Label>
                                        <p className="text-sm text-muted-foreground mt-1">
                                            If enabled, the system will try the provider with Priority 1. If it's down or runs out of credits, it instantly falls back to Priority 2.
                                        </p>
                                    </div>
                                </div>
                            </CardContent>
                            <CardFooter className="border-t bg-muted/10 py-4 justify-end">
                                <Button onClick={handleSaveGlobal} disabled={isSavingGlobal} className="w-full sm:w-auto shadow-sm">
                                    {isSavingGlobal && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} 
                                    Save Rules
                                </Button>
                            </CardFooter>
                        </Card>

                        <div className="bg-blue-500/10 border border-blue-500/20 text-blue-700 dark:text-blue-400 p-4 rounded-xl flex gap-3 text-sm">
                            <AlertTriangle className="w-5 h-5 shrink-0" />
                            <p><strong>Standardization:</strong> All providers must use OpenAI's standard JSON format for endpoints. Gemini now officially supports this via their compatibility endpoint.</p>
                        </div>
                    </div>

                    {/* --- Provider List Table --- */}
                    <div className="lg:col-span-2">
                        <Card className="shadow-sm border-border/50 h-full">
                            <CardHeader className="flex flex-row items-center justify-between bg-muted/10 border-b pb-4">
                                <div>
                                    <CardTitle>Configured Providers</CardTitle>
                                    <CardDescription>Available API endpoints.</CardDescription>
                                </div>
                                <Button onClick={() => openModal()}><PlusCircle className="mr-2 h-4 w-4"/> Add Model</Button>
                            </CardHeader>
                            <CardContent className="p-0">
                                <div className="overflow-x-auto w-full">
                                    <Table>
                                        <TableHeader>
                                            <TableRow className="bg-muted/40 text-muted-foreground">
                                                <TableHead className="pl-6">Provider / API Format</TableHead>
                                                <TableHead>Model / Auth</TableHead>
                                                <TableHead>Status</TableHead>
                                                <TableHead className="text-right pr-6">Actions</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {loading ? (
                                                <TableRow><TableCell colSpan={4} className="text-center h-32"><Loader2 className="w-6 h-6 animate-spin mx-auto text-muted-foreground"/></TableCell></TableRow>
                                            ) : providers.map(p => (
                                                <TableRow key={p.id}>
                                                    <TableCell className="pl-6 align-top">
                                                        <div className="font-bold text-foreground text-base">{p.provider_name}</div>
                                                        <div className="text-xs font-mono text-muted-foreground mt-0.5 truncate max-w-[200px]" title={p.api_endpoint}>
                                                            {p.api_endpoint}
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="align-top">
                                                        <Badge variant="outline" className="font-mono bg-background text-primary mb-1">{p.default_model}</Badge>
                                                        <div className="flex items-center gap-1 text-[10px] uppercase font-bold tracking-wider mt-1">
                                                            <KeyRound className="w-3 h-3 text-muted-foreground" />
                                                            {p.has_api_key ? <span className="text-green-500">Key Secured</span> : <span className="text-red-500">Missing Key</span>}
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="align-top">
                                                        <div className="flex flex-col gap-1 items-start">
                                                            {autoSelect ? (
                                                                <Badge className="bg-zinc-800 text-white">Priority: {p.priority}</Badge>
                                                            ) : (
                                                                p.is_default 
                                                                    ? <Badge className="bg-green-600 text-white">Default Active</Badge> 
                                                                    : <Badge variant="secondary">Standby</Badge>
                                                            )}
                                                            {!p.is_enabled && <Badge variant="destructive">Disabled</Badge>}
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right pr-6 align-top space-x-2">
                                                        {!autoSelect && !p.is_default && (
                                                            <Button size="icon" variant="ghost" onClick={() => handleSetActive(p.id)} title="Set as Manual Default" disabled={!p.is_enabled}>
                                                                <CheckCircle className="h-4 w-4 text-green-600" />
                                                            </Button>
                                                        )}
                                                        <Button size="icon" variant="ghost" onClick={() => openModal(p)} title="Edit Configuration">
                                                            <Edit className="h-4 w-4 text-blue-500" />
                                                        </Button>
                                                        {!p.is_default && (
                                                            <Button size="icon" variant="ghost" onClick={() => setDeleteId(p.id)} title="Delete Provider" className="hover:bg-red-50">
                                                                <Trash2 className="h-4 w-4 text-destructive" />
                                                            </Button>
                                                        )}
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                            {providers.length === 0 && !loading && (
                                                <TableRow>
                                                    <TableCell colSpan={4} className="text-center py-12 text-muted-foreground">
                                                        <BrainCircuit className="w-12 h-12 mx-auto opacity-20 mb-3" />
                                                        <p className="font-bold">No AI providers configured.</p>
                                                    </TableCell>
                                                </TableRow>
                                            )}
                                        </TableBody>
                                    </Table>
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>

                {/* --- Modal Form --- */}
                <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                    {/* 
                        FLEX-COL & MIN-H-0: 
                        This ensures the modal never grows larger than the screen and handles internal scrolling properly. 
                    */}
                    <DialogContent className="sm:max-w-2xl bg-card border-border/50 max-h-[90vh] flex flex-col p-0 overflow-hidden sm:rounded-2xl">
                        
                        <DialogHeader className="p-4 sm:p-6 border-b shrink-0 bg-muted/5">
                            <DialogTitle className="text-xl flex items-center gap-2">
                                <BrainCircuit className="w-5 h-5 text-primary" />
                                {editingProvider ? 'Edit AI Configuration' : 'Add Custom AI Provider'}
                            </DialogTitle>
                            <DialogDescription>
                                Works with any API that uses the OpenAI standard formatting.
                            </DialogDescription>
                        </DialogHeader>

                        {/* SCROLLABLE FORM BODY */}
                        <form id="ai-provider-form" onSubmit={handleModalSubmit} className="flex flex-col flex-1 min-h-0 overflow-hidden">
                            <div className="p-4 sm:p-6 py-4 space-y-6 overflow-y-auto flex-1 min-h-0 custom-scrollbar">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Provider Name <span className="text-red-500">*</span></Label>
                                        <Input value={formData.provider_name} onChange={e => setFormData({...formData, provider_name: e.target.value})} placeholder="e.g. DeepSeek" required className="bg-background"/>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Unique Slug <span className="text-red-500">*</span></Label>
                                        <Input value={formData.provider_key} onChange={e => setFormData({...formData, provider_key: e.target.value.toLowerCase()})} placeholder="deepseek" disabled={!!editingProvider} required={!editingProvider} className="bg-muted/50 font-mono"/>
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <Label>API Endpoint URL <span className="text-red-500">*</span></Label>
                                    <Input value={formData.api_endpoint} onChange={e => setFormData({...formData, api_endpoint: e.target.value})} placeholder="https://api.deepseek.com/v1/chat/completions" required className="bg-background font-mono text-sm" />
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Target Model Name <span className="text-red-500">*</span></Label>
                                        <Input value={formData.default_model} onChange={e => setFormData({...formData, default_model: e.target.value})} placeholder="e.g. deepseek-chat" required className="bg-background font-mono"/>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Fallback Priority (1 is Highest)</Label>
                                        <Input type="number" min="1" value={formData.priority} onChange={e => setFormData({...formData, priority: e.target.value})} className="bg-background" />
                                    </div>
                                </div>

                                <div className="space-y-2 pt-2 border-t border-border/50">
                                    <Label className="text-primary font-bold">API Secret Key {editingProvider ? '(Leave blank to keep current)' : '*'}</Label>
                                    <Input 
                                        type="password" 
                                        value={formData.api_key} 
                                        onChange={e => setFormData({...formData, api_key: e.target.value})} 
                                        placeholder={editingProvider ? "••••••••••••••••" : "sk-..."} 
                                        required={!editingProvider}
                                        className="bg-primary/5 border-primary/20 font-mono"
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label>Internal Notes</Label>
                                    <Textarea value={formData.notes} onChange={e => setFormData({...formData, notes: e.target.value})} placeholder="Costs, limits, context..." className="bg-background resize-none h-20"/>
                                </div>
                                
                                <div className="flex items-center p-4 border rounded-xl bg-muted/10 gap-3">
                                    <Switch id="is_enabled" checked={formData.is_enabled} onCheckedChange={c => setFormData({...formData, is_enabled: c})} />
                                    <Label htmlFor="is_enabled" className="cursor-pointer font-bold text-sm sm:text-base">Enable this provider for live queries</Label>
                                </div>
                            </div>

                            {/* STICKY FOOTER */}
                            <DialogFooter className="p-4 sm:p-6 border-t bg-muted/5 shrink-0 gap-2 sm:gap-0">
                                <Button type="button" variant="outline" className="w-full sm:w-auto" onClick={() => setIsModalOpen(false)}>Cancel</Button>
                                <Button type="submit" disabled={isSavingModal} className="shadow-sm w-full sm:w-auto">
                                    {isSavingModal && <Loader2 className="mr-2 h-4 w-4 animate-spin"/>} 
                                    Save Configuration
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

            </div>
        </AdminLayout>
    );
}