import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Switch } from "@/Components/ui/switch"; 
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, Languages, FileJson, Trash2, Save, ArrowRightLeft } from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal';

export default function LanguageManager() {
    const [languages, setLanguages] = useState([]);
    const [loading, setLoading] = useState(true);
    
    // Create State
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [newLang, setNewLang] = useState({ name: '', code: '', is_rtl: false });
    const [isCreating, setIsCreating] = useState(false);
    
    // Edit JSON State
    const [isEditOpen, setIsEditOpen] = useState(false);
    const [editingCode, setEditingCode] = useState(null);
    const [jsonContent, setJsonContent] = useState('');
    const [savingJson, setSavingJson] = useState(false);

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

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

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

    const handleCreate = async () => {
        if (!newLang.name || !newLang.code) {
            toast.error("Name and Code are required");
            return;
        }

        setIsCreating(true);
        try {
            await axios.post('/api/admin/languages', newLang);
            toast.success("Language added successfully");
            setIsCreateOpen(false);
            setNewLang({ name: '', code: '', is_rtl: false });
            fetchLanguages();
        } catch (e) { 
            toast.error(e.response?.data?.message || "Failed to add language"); 
        } finally {
            setIsCreating(false);
        }
    };

    const handleSetDefault = async (id) => {
        try {
            await axios.post(`/api/admin/languages/${id}/default`);
            toast.success("Default language updated");
            fetchLanguages();
        } catch (e) { 
            toast.error("Failed to update default language"); 
        }
    };

    // 1. Trigger Modal
    const confirmDelete = (id) => {
        setDeleteId(id);
        setIsDeleteOpen(true);
    };

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

    const openEditor = async (code) => {
        setEditingCode(code);
        setJsonContent('Loading translations...');
        setIsEditOpen(true);
        try {
            const res = await axios.get(`/api/admin/languages/${code}/translations`);
            const parsed = JSON.parse(res.data.content);
            setJsonContent(JSON.stringify(parsed, null, 4));
        } catch (e) {
            setJsonContent('{\n    \n}');
        }
    };

    const saveJson = async () => {
        setSavingJson(true);
        try {
            JSON.parse(jsonContent); 
            await axios.put(`/api/admin/languages/${editingCode}/translations`, { content: jsonContent });
            toast.success("Translations saved successfully!");
            setIsEditOpen(false);
        } catch (e) {
            if (e instanceof SyntaxError) {
                toast.error("Invalid JSON format. Please check your syntax.");
            } else {
                toast.error("Failed to save translations");
            }
        } finally {
            setSavingJson(false);
        }
    };

    return (
        <AdminLayout>
            <Head title="Languages" />
            <SettingsLayout>
                
                {/* --- Global Delete Modal --- */}
                <ConfirmModal 
                    open={isDeleteOpen}
                    onOpenChange={setIsDeleteOpen}
                    onConfirm={handleDelete}
                    title="Delete Language?"
                    description="This will remove the language from the system. The translation file will remain on the server but will be inactive."
                    confirmText="Delete Language"
                    variant="destructive"
                />

                <div className="space-y-6">
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle className="flex items-center gap-2">
                                    <Languages className="w-5 h-5 text-primary" /> Language Management
                                </CardTitle>
                                <CardDescription>Add languages, configure RTL support, and edit translations.</CardDescription>
                            </div>
                            <Button onClick={() => setIsCreateOpen(true)}>
                                <PlusCircle className="mr-2 h-4 w-4"/> Add Language
                            </Button>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Name</TableHead>
                                        <TableHead>Code</TableHead>
                                        <TableHead>Direction</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead className="text-right">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {loading ? (
                                        <TableRow><TableCell colSpan={5} className="text-center py-8">Loading...</TableCell></TableRow>
                                    ) : languages.length === 0 ? (
                                        <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No languages found.</TableCell></TableRow>
                                    ) : (
                                        languages.map(lang => (
                                            <TableRow key={lang.id}>
                                                <TableCell className="font-medium">{lang.name}</TableCell>
                                                <TableCell>
                                                    <Badge variant="outline" className="uppercase font-mono">{lang.code}</Badge>
                                                </TableCell>
                                                <TableCell>
                                                    {lang.is_rtl ? (
                                                        <Badge variant="secondary" className="flex w-fit items-center gap-1">
                                                            <ArrowRightLeft className="w-3 h-3" /> RTL
                                                        </Badge>
                                                    ) : (
                                                        <span className="text-xs text-muted-foreground">LTR</span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    {lang.is_default && <Badge className="bg-green-600 hover:bg-green-700">Default</Badge>}
                                                </TableCell>
                                                <TableCell className="text-right space-x-2">
                                                    {!lang.is_default && (
                                                        <Button size="icon" variant="ghost" onClick={() => handleSetDefault(lang.id)} title="Set as Default">
                                                            <CheckCircle className="h-4 w-4 text-muted-foreground hover:text-green-600" />
                                                        </Button>
                                                    )}
                                                    <Button size="sm" variant="secondary" onClick={() => openEditor(lang.code)}>
                                                        <FileJson className="h-4 w-4 mr-2" /> Edit JSON
                                                    </Button>
                                                    {!lang.is_default && (
                                                        <Button 
                                                            size="icon" 
                                                            variant="ghost" 
                                                            className="text-red-500 hover:text-red-700 hover:bg-red-50" 
                                                            onClick={() => confirmDelete(lang.id)}
                                                        >
                                                            <Trash2 className="h-4 w-4" />
                                                        </Button>
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                </div>

                {/* Create Language Modal */}
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Add New Language</DialogTitle>
                        </DialogHeader>
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label>Language Name</Label>
                                <Input 
                                    value={newLang.name} 
                                    onChange={e => setNewLang({...newLang, name: e.target.value})} 
                                    placeholder="e.g. Arabic" 
                                />
                            </div>
                            <div className="space-y-2">
                                <Label>ISO Code</Label>
                                <Input 
                                    value={newLang.code} 
                                    onChange={e => setNewLang({...newLang, code: e.target.value})} 
                                    placeholder="e.g. ar" 
                                    maxLength={5} 
                                />
                                <p className="text-xs text-muted-foreground">Use standard ISO codes (en, bn, ar, fr).</p>
                            </div>
                            
                            {/* RTL Switch */}
                            <div className="flex items-center justify-between border p-3 rounded-md bg-muted/20">
                                <div className="space-y-0.5">
                                    <Label className="text-base">RTL Mode</Label>
                                    <p className="text-xs text-muted-foreground">Enable for Right-to-Left languages (Arabic, Hebrew).</p>
                                </div>
                                <Switch 
                                    checked={newLang.is_rtl} 
                                    onCheckedChange={(c) => setNewLang({...newLang, is_rtl: c})} 
                                />
                            </div>

                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsCreateOpen(false)}>Cancel</Button>
                                <Button onClick={handleCreate} disabled={isCreating}>
                                    {isCreating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                    Create Language
                                </Button>
                            </DialogFooter>
                        </div>
                    </DialogContent>
                </Dialog>

                {/* Edit JSON Modal */}
                <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
                    <DialogContent className="max-w-4xl h-[80vh] flex flex-col">
                        <DialogHeader>
                            <DialogTitle className="flex items-center gap-2">
                                <FileJson className="w-5 h-5 text-yellow-600" />
                                Edit Translations: <span className="uppercase font-mono text-primary">{editingCode}</span>
                            </DialogTitle>
                        </DialogHeader>
                        
                        <div className="flex-1 min-h-0 flex flex-col gap-2">
                            <div className="text-xs text-muted-foreground bg-muted p-2 rounded border">
                                <strong>Tip:</strong> Ensure valid JSON format. Example: <code>{`"_home": "Home Page"`}</code>
                            </div>
                            <Textarea 
                                className="font-mono text-sm leading-relaxed h-full resize-none bg-slate-50 dark:bg-slate-950 border-slate-200 dark:border-slate-800" 
                                value={jsonContent} 
                                onChange={e => setJsonContent(e.target.value)} 
                                spellCheck="false"
                            />
                        </div>

                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsEditOpen(false)}>Cancel</Button>
                            <Button onClick={saveJson} disabled={savingJson}>
                                {savingJson ? <Loader2 className="animate-spin mr-2 h-4 w-4"/> : <Save className="mr-2 h-4 w-4"/>} 
                                Save Changes
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

            </SettingsLayout>
        </AdminLayout>
    );
}