import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } 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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/Components/ui/dropdown-menu";
import { Loader2, Save, BrainCircuit, PlusCircle, MoreHorizontal, Edit, Trash2, CheckCircle, Power } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';
import ConfirmModal from '@/Components/ConfirmModal';

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

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

    // --- Data Fetching ---
    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = () => {
        setLoading(true);
        Promise.all([
            axios.get('/api/admin/settings/ai'),
            axios.get('/api/admin/ai-providers')
        ]).then(([settingsRes, providersRes]) => {
            setAutoSelect(settingsRes.data.ai_auto_select_enabled);
            setProviders(providersRes.data);
        }).catch(() => {
            toast.error("Failed to load AI settings.");
        }).finally(() => {
            setLoading(false);
        });
    };

    // --- Handlers ---
    const handleSaveGlobal = async () => {
        setIsSavingGlobal(true);
        try {
            await axios.post('/api/admin/settings/ai', { ai_auto_select_enabled: autoSelect });
            toast.success("Global settings updated.");
        } catch (e) { toast.error("Failed to save 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: '', // Always 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 
            ? `/api/admin/ai-providers/${editingProvider.id}` 
            : '/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) => {
        try {
            const res = await axios.post(`/api/admin/ai-providers/${id}/set-active`);
            toast.success(res.data.message);
            fetchData();
        } catch (error) {
            toast.error(error.response?.data?.message || "Failed to activate.");
        }
    };
    
    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            const res = await axios.delete(`/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 Providers" />
            <SettingsLayout>
                
                <ConfirmModal 
                    open={!!deleteId} 
                    onOpenChange={() => setDeleteId(null)}
                    onConfirm={handleDelete}
                    title="Delete AI Provider?"
                    description="This action cannot be undone. Make sure no services depend on this provider."
                    variant="destructive"
                />

                <div className="space-y-6">
                    {/* --- Global Settings Card --- */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2"><BrainCircuit className="w-5 h-5" /> Global AI Settings</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="flex items-center justify-between rounded-lg border p-4">
                                <div>
                                    <Label>Auto-Select Provider</Label>
                                    <p className="text-sm text-muted-foreground">Automatically select the best provider based on priority.</p>
                                </div>
                                <Switch checked={autoSelect} onCheckedChange={setAutoSelect} />
                            </div>
                        </CardContent>
                        <div className="px-6 py-4 border-t">
                            <Button onClick={handleSaveGlobal} disabled={isSavingGlobal}>
                                {isSavingGlobal && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} Save Global Setting
                            </Button>
                        </div>
                    </Card>

                    {/* --- Provider Management Card --- */}
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle>AI Providers</CardTitle>
                                <CardDescription>Manage your available AI API providers.</CardDescription>
                            </div>
                            <Button onClick={() => openModal()}><PlusCircle className="mr-2 h-4 w-4"/> Add Provider</Button>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Provider</TableHead>
                                        <TableHead>Default Model</TableHead>
                                        <TableHead>Priority</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead className="text-right">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {loading ? <TableRow><TableCell colSpan={5} className="text-center h-24">Loading...</TableCell></TableRow> :
                                    providers.map(p => (
                                        <TableRow key={p.id}>
                                            <TableCell className="font-medium">
                                                <div>{p.provider_name}</div>
                                                <div className="text-xs text-muted-foreground font-mono">{p.provider_key}</div>
                                            </TableCell>
                                            <TableCell><Badge variant="outline">{p.default_model}</Badge></TableCell>
                                            <TableCell>{p.priority}</TableCell>
                                            <TableCell>
                                                <div className="flex gap-2">
                                                    {p.is_active && <Badge className="bg-green-600 hover:bg-green-700">Active</Badge>}
                                                    <Badge variant={p.is_enabled ? "secondary" : "destructive"}>{p.is_enabled ? 'Enabled' : 'Disabled'}</Badge>
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild><Button variant="ghost" size="icon"><MoreHorizontal /></Button></DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end">
                                                        <DropdownMenuItem onClick={() => openModal(p)}><Edit className="mr-2 h-4 w-4" /> Edit</DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => handleSetActive(p.id)} disabled={p.is_active || !p.is_enabled}><CheckCircle className="mr-2 h-4 w-4"/> Set Active</DropdownMenuItem>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem onClick={() => setDeleteId(p.id)} disabled={p.is_active} className="text-red-600 focus:text-red-600"><Trash2 className="mr-2 h-4 w-4"/> Delete</DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                </div>
                
                {/* --- Modal Form --- */}
                <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                    <DialogContent className="sm:max-w-2xl">
                        <DialogHeader>
                            <DialogTitle>{editingProvider ? 'Edit Provider' : 'Add New Provider'}</DialogTitle>
                        </DialogHeader>
                        <form onSubmit={handleModalSubmit} className="space-y-4 py-2">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-1"><Label>Provider Name</Label><Input value={formData.provider_name} onChange={e => setFormData({...formData, provider_name: e.target.value})} placeholder="OpenAI GPT-4" required /></div>
                                <div className="space-y-1"><Label>Provider Key</Label><Input value={formData.provider_key} onChange={e => setFormData({...formData, provider_key: e.target.value})} placeholder="openai" disabled={!!editingProvider} required={!editingProvider}/></div>
                            </div>
                            <div className="space-y-1"><Label>API Endpoint</Label><Input value={formData.api_endpoint} onChange={e => setFormData({...formData, api_endpoint: e.target.value})} placeholder="https://api.openai.com/v1/chat/completions" required /></div>
                            <div className="space-y-1"><Label>API Key</Label><Input type="password" value={formData.api_key} onChange={e => setFormData({...formData, api_key: e.target.value})} placeholder={editingProvider ? "Leave blank to keep unchanged" : ""} /></div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-1"><Label>Default Model</Label><Input value={formData.default_model} onChange={e => setFormData({...formData, default_model: e.target.value})} placeholder="gpt-4-turbo" required /></div>
                                <div className="space-y-1"><Label>Priority</Label><Input type="number" value={formData.priority} onChange={e => setFormData({...formData, priority: e.target.value})} /></div>
                            </div>
                            <div className="space-y-1"><Label>Notes</Label><Textarea value={formData.notes} onChange={e => setFormData({...formData, notes: e.target.value})} placeholder="Optional notes..."/></div>
                            <div className="flex items-center space-x-2"><Switch id="is_enabled" checked={formData.is_enabled} onCheckedChange={c => setFormData({...formData, is_enabled: c})} /><Label htmlFor="is_enabled">Enable this provider</Label></div>

                            <DialogFooter>
                                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>Cancel</Button>
                                <Button type="submit" disabled={isSavingModal}>{isSavingModal && <Loader2 className="mr-2 h-4 w-4 animate-spin"/>} Save Provider</Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

            </SettingsLayout>
        </AdminLayout>
    );
}