import { Head, router } from '@inertiajs/react';
import { useState } from 'react';
import { Plus, Edit, Trash2, MessageSquare, Users, Eye, EyeOff, ChevronRight } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
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 { Badge } from '@/components/ui/badge';
import { useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import { 
    index as forumsIndex, 
    store as forumStore, 
    update as forumUpdate, 
    destroy as forumDestroy,
    threads as forumThreads 
} from '@/actions/App/Http/Controllers/Admin/ForumManagementController';

interface Forum {
    id: number;
    name: string;
    slug: string;
    description: string;
    order: number;
    is_active: boolean;
    threads_count: number;
    posts_count: number;
    created_at: string;
}

interface Props {
    forums: Forum[];
}

export default function AdminForumsIndex({ forums }: Props) {
    const [createModalOpen, setCreateModalOpen] = useState(false);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [selectedForum, setSelectedForum] = useState<Forum | null>(null);

    const createForm = useForm({
        name: '',
        slug: '',
        description: '',
        order: forums.length + 1,
        is_active: true,
    });

    const editForm = useForm({
        name: '',
        slug: '',
        description: '',
        order: 0,
        is_active: true,
    });

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(forumStore.url(), {
            onSuccess: () => {
                setCreateModalOpen(false);
                createForm.reset();
                toast.success('Foro creado exitosamente');
            },
        });
    };

    const handleEdit = (forum: Forum) => {
        setSelectedForum(forum);
        editForm.setData({
            name: forum.name,
            slug: forum.slug,
            description: forum.description,
            order: forum.order,
            is_active: forum.is_active,
        });
        setEditModalOpen(true);
    };

    const handleUpdate = (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedForum) return;

        editForm.put(forumUpdate.url(selectedForum.id), {
            onSuccess: () => {
                setEditModalOpen(false);
                setSelectedForum(null);
                toast.success('Foro actualizado exitosamente');
            },
        });
    };

    const handleDelete = (forum: Forum) => {
        if (!confirm(`¿Estás seguro de eliminar el foro "${forum.name}"?`)) return;

        router.delete(forumDestroy.url(forum.id), {
            onSuccess: () => toast.success('Foro eliminado'),
            onError: (errors) => toast.error(errors.error || 'Error al eliminar'),
        });
    };

    return (
        <AppLayout>
            <Head title="Gestión de Foros" />

            <div className="p-6 space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-3xl font-bold">Gestión de Foros</h1>
                        <p className="text-muted-foreground mt-1">
                            Administra las categorías y salas de discusión
                        </p>
                    </div>
                    <Button onClick={() => setCreateModalOpen(true)} className="bg-forest hover:bg-forest-light">
                        <Plus className="mr-2 h-4 w-4" />
                        Crear Foro
                    </Button>
                </div>

                {/* Forums List */}
                <div className="grid gap-4">
                    {forums.map((forum) => (
                        <Card key={forum.id} className={!forum.is_active ? 'opacity-60' : ''}>
                            <div className="p-6">
                                <div className="flex items-start justify-between gap-4">
                                    <div className="flex-1">
                                        <div className="flex items-center gap-3 mb-2">
                                            <MessageSquare className="h-5 w-5 text-forest" />
                                            <CardTitle className="text-xl">{forum.name}</CardTitle>
                                            {!forum.is_active && (
                                                <Badge variant="secondary" className="gap-1">
                                                    <EyeOff className="h-3 w-3" /> Inactivo
                                                </Badge>
                                            )}
                                            <Badge variant="outline">Orden: {forum.order}</Badge>
                                        </div>
                                        <CardDescription className="text-base mb-4">
                                            {forum.description}
                                        </CardDescription>
                                        
                                        <div className="flex items-center gap-6 text-sm text-muted-foreground">
                                            <div className="flex items-center gap-1">
                                                <MessageSquare className="h-4 w-4" />
                                                {forum.threads_count} hilos
                                            </div>
                                            <div className="flex items-center gap-1">
                                                <Users className="h-4 w-4" />
                                                {forum.posts_count} comentarios
                                            </div>
                                        </div>
                                    </div>

                                    <div className="flex items-center gap-2">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => router.visit(forumThreads.url(forum.id))}
                                        >
                                            Ver Hilos
                                            <ChevronRight className="ml-1 h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => handleEdit(forum)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => handleDelete(forum)}
                                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </Card>
                    ))}
                </div>

                {/* Create Modal */}
                <Dialog open={createModalOpen} onOpenChange={setCreateModalOpen}>
                    <DialogContent className="sm:max-w-[600px]">
                        <DialogHeader>
                            <DialogTitle>Crear Nuevo Foro</DialogTitle>
                            <DialogDescription>
                                Crea una nueva categoría o sala de discusión
                            </DialogDescription>
                        </DialogHeader>
                        <form onSubmit={handleCreate} className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="create-name">Nombre del Foro</Label>
                                <Input
                                    id="create-name"
                                    value={createForm.data.name}
                                    onChange={(e) => createForm.setData('name', e.target.value)}
                                    placeholder="Ej: Foro 3: Nuevos Proyectos"
                                    required
                                />
                                {createForm.errors.name && <p className="text-sm text-red-500">{createForm.errors.name}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-slug">Slug (URL amigable)</Label>
                                <Input
                                    id="create-slug"
                                    value={createForm.data.slug}
                                    onChange={(e) => createForm.setData('slug', e.target.value)}
                                    placeholder="nuevos-proyectos"
                                    required
                                />
                                {createForm.errors.slug && <p className="text-sm text-red-500">{createForm.errors.slug}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-description">Descripción</Label>
                                <Textarea
                                    id="create-description"
                                    value={createForm.data.description}
                                    onChange={(e) => createForm.setData('description', e.target.value)}
                                    placeholder="Describe el propósito de este foro..."
                                    className="min-h-[100px]"
                                    required
                                />
                                {createForm.errors.description && <p className="text-sm text-red-500">{createForm.errors.description}</p>}
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="create-order">Orden</Label>
                                    <Input
                                        id="create-order"
                                        type="number"
                                        min="0"
                                        value={createForm.data.order}
                                        onChange={(e) => createForm.setData('order', parseInt(e.target.value))}
                                        required
                                    />
                                </div>
                                <div className="flex items-center space-x-2 pt-8">
                                    <Switch
                                        id="create-active"
                                        checked={createForm.data.is_active}
                                        onCheckedChange={(checked: boolean) => createForm.setData('is_active', checked)}
                                    />
                                    <Label htmlFor="create-active">Activo</Label>
                                </div>
                            </div>
                            <DialogFooter>
                                <Button type="button" variant="outline" onClick={() => setCreateModalOpen(false)}>
                                    Cancelar
                                </Button>
                                <Button type="submit" disabled={createForm.processing} className="bg-forest hover:bg-forest-light">
                                    {createForm.processing ? 'Creando...' : 'Crear Foro'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Modal */}
                <Dialog open={editModalOpen} onOpenChange={setEditModalOpen}>
                    <DialogContent className="sm:max-w-[600px]">
                        <DialogHeader>
                            <DialogTitle>Editar Foro</DialogTitle>
                            <DialogDescription>
                                Actualiza la información del foro
                            </DialogDescription>
                        </DialogHeader>
                        <form onSubmit={handleUpdate} className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="edit-name">Nombre del Foro</Label>
                                <Input
                                    id="edit-name"
                                    value={editForm.data.name}
                                    onChange={(e) => editForm.setData('name', e.target.value)}
                                    required
                                />
                                {editForm.errors.name && <p className="text-sm text-red-500">{editForm.errors.name}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="edit-slug">Slug</Label>
                                <Input
                                    id="edit-slug"
                                    value={editForm.data.slug}
                                    onChange={(e) => editForm.setData('slug', e.target.value)}
                                    required
                                />
                                {editForm.errors.slug && <p className="text-sm text-red-500">{editForm.errors.slug}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="edit-description">Descripción</Label>
                                <Textarea
                                    id="edit-description"
                                    value={editForm.data.description}
                                    onChange={(e) => editForm.setData('description', e.target.value)}
                                    className="min-h-[100px]"
                                    required
                                />
                                {editForm.errors.description && <p className="text-sm text-red-500">{editForm.errors.description}</p>}
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="edit-order">Orden</Label>
                                    <Input
                                        id="edit-order"
                                        type="number"
                                        min="0"
                                        value={editForm.data.order}
                                        onChange={(e) => editForm.setData('order', parseInt(e.target.value))}
                                        required
                                    />
                                </div>
                                <div className="flex items-center space-x-2 pt-8">
                                    <Switch
                                        id="edit-active"
                                        checked={editForm.data.is_active}
                                        onCheckedChange={(checked: boolean) => editForm.setData('is_active', checked)}
                                    />
                                    <Label htmlFor="edit-active">Activo</Label>
                                </div>
                            </div>
                            <DialogFooter>
                                <Button type="button" variant="outline" onClick={() => setEditModalOpen(false)}>
                                    Cancelar
                                </Button>
                                <Button type="submit" disabled={editForm.processing} className="bg-forest hover:bg-forest-light">
                                    {editForm.processing ? 'Actualizando...' : 'Actualizar Foro'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>
            </div>
        </AppLayout>
    );
}
