// resources/js/Pages/cp/Settings/LanguageManager.jsx
import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner'; // <-- Import toast from sonner
import AdminLayout from '@/cp/Layouts/AdminLayout';
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 { 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('/cp/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) {
            return toast.error("Name and Code are required");
        }
        
        setIsCreating(true);
        try {
            await axios.post('/cp/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(`/cp/api/admin/languages/${id}/default`);
            toast.success("Default language updated successfully");
            fetchLanguages();
        } catch (e) { 
            toast.error("Failed to update default language"); 
        }
    };

    const confirmDelete = (id) => { 
        setDeleteId(id); 
        setIsDeleteOpen(true); 
    };

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

    const openEditor = async (code) => {
        setEditingCode(code);
        setJsonContent('Loading translations...');
        setIsEditOpen(true);
        try {
            const res = await axios.get(`/cp/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(`/cp/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 for missing commas or quotes.");
            } else {
                toast.error("Failed to save translations");
            }
        } finally { 
            setSavingJson(false); 
        }
    };

    return (
        <AdminLayout>
            <Head title="Languages" />
            
            <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."
                confirmText="Delete Language"
                variant="destructive"
            />

            <div className="max-w-6xl mx-auto space-y-6">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between border-b bg-muted/10 pb-4">
                        <div>
                            <CardTitle className="flex items-center gap-2">
                                <Languages className="w-5 h-5 text-primary" /> Language Manager
                            </CardTitle>
                            <CardDescription className="mt-1">Add languages, configure RTL, and edit translations.</CardDescription>
                        </div>
                        <Button onClick={() => setIsCreateOpen(true)}>
                            <PlusCircle className="mr-2 h-4 w-4"/> Add Language
                        </Button>
                    </CardHeader>
                    <CardContent className="p-0">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="pl-6">Name</TableHead>
                                    <TableHead>Code</TableHead>
                                    <TableHead>Direction</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>
                                ) : languages.map(lang => (
                                    <TableRow key={lang.id}>
                                        <TableCell className="font-medium pl-6">{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 text-white">Default</Badge>}</TableCell>
                                        <TableCell className="text-right pr-6 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 Dialog */}
            <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} />
                        </div>
                        <div className="flex items-center justify-between border p-3 rounded-md bg-muted/20">
                            <div>
                                <Label className="text-base">RTL Mode</Label>
                                <p className="text-xs text-muted-foreground">Enable for Right-to-Left languages.</p>
                            </div>
                            <input type="checkbox" className="w-5 h-5 rounded border-gray-300 text-primary" checked={newLang.is_rtl} onChange={(e) => setNewLang({...newLang, is_rtl: e.target.checked})} />
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsCreateOpen(false)}>Cancel</Button>
                            <Button onClick={handleCreate} disabled={isCreating}>Create Language</Button>
                        </DialogFooter>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Edit JSON Dialog */}
            <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">
                        <Textarea 
                            className="font-mono text-sm leading-relaxed h-full resize-none bg-zinc-950 text-zinc-100 p-4" 
                            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>
        </AdminLayout>
    );
}