import React, { useEffect, useState } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    DndContext, 
    closestCenter, 
    KeyboardSensor, 
    PointerSensor, 
    useSensor, 
    useSensors 
} from '@dnd-kit/core';
import { 
    arrayMove, 
    SortableContext, 
    sortableKeyboardCoordinates, 
    verticalListSortingStrategy 
} from '@dnd-kit/sortable';

import AdminLayout from '@/Admin/Layouts/AdminLayout';
import { Input } from '@/Components/ui/input';
import { Button } from '@/Components/ui/button';
import { Label } from '@/Components/ui/label';
import { Badge } from '@/Components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/Components/ui/tabs";
import { PlusCircle, Search, Edit, Trash2, Folder, CornerDownRight, Loader2, Save, ListTree, Table as TableIcon } from 'lucide-react';

import { SortableItem } from './SortableItem';

export default function CategoryManager() {
    const [categories, setCategories] = useState([]); // Flat list for table
    const [treeData, setTreeData] = useState([]);     // Tree data for reorder
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [viewMode, setViewMode] = useState('table'); // 'table' or 'reorder'

    // Modal State
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingCategory, setEditingCategory] = useState(null);
    const [formLoading, setFormLoading] = useState(false);
    const [formData, setFormData] = useState({ name: '', parent_id: 'none' });

    // DnD Sensors
    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
    );

    // Initial Fetch
    useEffect(() => {
        fetchCategories();
    }, [search]);

    const fetchCategories = async () => {
        setLoading(true);
        try {
            // Fetch Flat for Table
            const resFlat = await axios.get(`/api/admin/categories?search=${search}`);
            setCategories(resFlat.data);

            // Fetch Tree for Reorder (if no search active)
            if (!search) {
                const resTree = await axios.get('/api/admin/categories?tree=true');
                setTreeData(resTree.data);
            }
        } catch (error) {
            toast.error("Failed to load categories");
        } finally {
            setLoading(false);
        }
    };

    // --- DRAG END HANDLER ---
    const handleDragEnd = (event) => {
        const { active, over } = event;
        if (!over || active.id === over.id) return;

        // Determine if we are sorting roots or children
        const isRoot = treeData.find(c => c.id === active.id);
        
        if (isRoot) {
            // Sorting Root Categories
            const oldIndex = treeData.findIndex((c) => c.id === active.id);
            const newIndex = treeData.findIndex((c) => c.id === over.id);
            const newOrder = arrayMove(treeData, oldIndex, newIndex);
            setTreeData(newOrder);
            saveOrder(newOrder); // Save roots
        } else {
            // Sorting Children (Find parent first)
            const parent = treeData.find(p => p.children.some(c => c.id === active.id));
            if (parent) {
                const subItems = parent.children;
                const oldIndex = subItems.findIndex((c) => c.id === active.id);
                const newIndex = subItems.findIndex((c) => c.id === over.id);
                const newSubOrder = arrayMove(subItems, oldIndex, newIndex);
                
                // Update Tree Data Locally
                const newTree = treeData.map(p => {
                    if (p.id === parent.id) return { ...p, children: newSubOrder };
                    return p;
                });
                setTreeData(newTree);
                saveOrder(newSubOrder, parent.id); // Save specific children list
            }
        }
    };

    const saveOrder = async (items, parentId = null) => {
        const payload = items.map((item, index) => ({
            id: item.id,
            order: index,
            parent_id: parentId
        }));

        try {
            await axios.post('/api/admin/categories/reorder', { categories: payload });
            toast.success("Order saved");
        } catch (error) {
            toast.error("Failed to save order");
        }
    };

    // --- CRUD Handlers ---
    const openModal = (category = null) => {
        if (category) {
            setEditingCategory(category);
            setFormData({
                name: category.name,
                parent_id: category.parent_id ? String(category.parent_id) : 'none'
            });
        } else {
            setEditingCategory(null);
            setFormData({ name: '', parent_id: 'none' });
        }
        setIsModalOpen(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setFormLoading(true);
        const payload = {
            name: formData.name,
            parent_id: formData.parent_id === 'none' ? null : formData.parent_id
        };

        try {
            if (editingCategory) {
                await axios.put(`/api/admin/categories/${editingCategory.id}`, payload);
                toast.success("Category updated");
            } else {
                await axios.post('/api/admin/categories', payload);
                toast.success("Category created");
            }
            setIsModalOpen(false);
            fetchCategories();
        } catch (error) {
            toast.error("Operation failed");
        } finally {
            setFormLoading(false);
        }
    };

    const handleDelete = async (id) => {
        if (!confirm("Delete category?")) return;
        try {
            await axios.delete(`/api/admin/categories/${id}`);
            toast.success("Deleted");
            fetchCategories();
        } catch (error) {
            toast.error("Failed");
        }
    };

    return (
        <AdminLayout header="Categories">
            <Head title="Category Management" />

            <div className="flex flex-col sm:flex-row justify-between items-center mb-6 gap-4">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">Categories</h2>
                    <p className="text-muted-foreground">Manage hierarchy and ordering.</p>
                </div>
                <div className="flex items-center gap-2">
                    <Tabs value={viewMode} onValueChange={setViewMode} className="mr-4">
                        <TabsList>
                            <TabsTrigger value="table"><TableIcon className="w-4 h-4 mr-2"/> Table</TabsTrigger>
                            <TabsTrigger value="reorder"><ListTree className="w-4 h-4 mr-2"/> Reorder</TabsTrigger>
                        </TabsList>
                    </Tabs>
                    <Button onClick={() => openModal()}>
                        <PlusCircle className="mr-2 h-4 w-4" /> Add Category
                    </Button>
                </div>
            </div>

            {viewMode === 'table' ? (
                // --- TABLE VIEW ---
                <Card>
                    <CardHeader className="p-4 flex flex-row items-center justify-between">
                        <CardTitle>Category List</CardTitle>
                        <div className="relative w-64">
                            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                            <Input placeholder="Search..." className="pl-8" value={search} onChange={(e) => setSearch(e.target.value)} />
                        </div>
                    </CardHeader>
                    <CardContent className="p-0">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-[50px]"></TableHead>
                                    <TableHead>Name</TableHead>
                                    <TableHead>Slug</TableHead>
                                    <TableHead>Parent</TableHead>
                                    <TableHead className="text-right">Actions</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {categories.map((cat) => (
                                    <TableRow key={cat.id}>
                                        <TableCell className="text-center">
                                            {cat.parent_id ? <CornerDownRight className="h-4 w-4 text-muted-foreground ml-auto" /> : <Folder className="h-4 w-4 text-primary" />}
                                        </TableCell>
                                        <TableCell className="font-medium">{cat.name}</TableCell>
                                        <TableCell className="text-muted-foreground text-sm">/{cat.slug}</TableCell>
                                        <TableCell>{cat.parent ? <Badge variant="outline">{cat.parent.name}</Badge> : '-'}</TableCell>
                                        <TableCell className="text-right space-x-2">
                                            <Button variant="ghost" size="icon" onClick={() => openModal(cat)}><Edit className="h-4 w-4" /></Button>
                                            <Button variant="ghost" size="icon" className="text-red-600" onClick={() => handleDelete(cat.id)}><Trash2 className="h-4 w-4" /></Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            ) : (
                // --- REORDER VIEW (Drag & Drop) ---
                <Card>
                    <CardHeader>
                        <CardTitle>Reorder Categories</CardTitle>
                        <p className="text-sm text-muted-foreground">Drag items to reorder. Root categories and sub-categories are sorted independently.</p>
                    </CardHeader>
                    <CardContent className="p-6">
                        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
                            <SortableContext items={treeData.map(c => c.id)} strategy={verticalListSortingStrategy}>
                                {treeData.map((root) => (
                                    <div key={root.id} className="mb-4">
                                        {/* Root Item */}
                                        <SortableItem id={root.id} category={root} onEdit={openModal} onDelete={handleDelete} />
                                        
                                        {/* Sub Items Container */}
                                        {root.children && root.children.length > 0 && (
                                            <div className="pl-4 border-l-2 border-muted ml-4 mt-2">
                                                <SortableContext items={root.children.map(c => c.id)} strategy={verticalListSortingStrategy}>
                                                    {root.children.map((child) => (
                                                        <SortableItem 
                                                            key={child.id} 
                                                            id={child.id} 
                                                            category={child} 
                                                            isSubItem={true} 
                                                            onEdit={openModal} 
                                                            onDelete={handleDelete} 
                                                        />
                                                    ))}
                                                </SortableContext>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </SortableContext>
                        </DndContext>
                    </CardContent>
                </Card>
            )}

            {/* Modal (Same as before) */}
            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{editingCategory ? 'Edit Category' : 'Create Category'}</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div className="space-y-2">
                            <Label>Name</Label>
                            <Input value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} required />
                        </div>
                        <div className="space-y-2">
                            <Label>Parent</Label>
                            <Select value={formData.parent_id} onValueChange={(val) => setFormData({...formData, parent_id: val})}>
                                <SelectTrigger><SelectValue placeholder="Select Parent" /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="none">Root Level</SelectItem>
                                    {categories.filter(c => c.parent_id === null && c.id !== editingCategory?.id).map(c => (
                                        <SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <DialogFooter>
                            <Button type="submit" disabled={formLoading}>{formLoading ? <Loader2 className="animate-spin h-4 w-4" /> : 'Save'}</Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </AdminLayout>
    );
}