import { Head, router, useForm } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { index, store, update, destroy } from '@/actions/App/Http/Controllers/Admin/UserController';
import { assignRole } from '@/actions/App/Http/Controllers/Admin/UserController';
import { 
    Users, 
    Search, 
    Plus, 
    MoreVertical, 
    Trash2, 
    Edit, 
    UserCog,
    Filter,
    X
} from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import { UserRoleBadge } from '@/components/admin/user-role-badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { 
    Dialog, 
    DialogContent, 
    DialogDescription, 
    DialogFooter, 
    DialogHeader, 
    DialogTitle 
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
    DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';

interface User {
    id: number;
    name: string;
    email: string;
    age?: number;
    gender?: string;
    country?: string;
    entheogen_activity?: string;
    roles: string[];
    primary_role: string;
    created_at: string;
    created_at_human: string;
}

interface PaginatedUsers {
    data: User[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
}

interface Props {
    users: PaginatedUsers;
    roles: string[];
    filters: {
        search?: string;
        role?: string;
    };
}

export default function UsersIndex({ users, roles, filters }: Props) {
    const [createModalOpen, setCreateModalOpen] = useState(false);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [roleModalOpen, setRoleModalOpen] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [searchTerm, setSearchTerm] = useState(filters.search || '');
    const [roleFilter, setRoleFilter] = useState(filters.role || 'all');

    const createForm = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
        age: '',
        gender: '',
        country: '',
        entheogen_activity: '',
        role: 'user',
    });

    const editForm = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
        age: '',
        gender: '',
        country: '',
        entheogen_activity: '',
        role: '',
    });

    const roleForm = useForm({
        role: '',
    });

    // Dynamic search with debounce
    useEffect(() => {
        const debounceTimer = setTimeout(() => {
            router.get(index.url(), {
                search: searchTerm || undefined,
                role: roleFilter === 'all' ? undefined : roleFilter,
            }, { 
                preserveState: true,
                preserveScroll: true,
            });
        }, 500); // 500ms debounce

        return () => clearTimeout(debounceTimer);
    }, [searchTerm, roleFilter]);

    const clearFilters = () => {
        setSearchTerm('');
        setRoleFilter('all');
    };

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(store.url(), {
            onSuccess: () => {
                setCreateModalOpen(false);
                createForm.reset();
                toast.success('Usuario creado exitosamente');
            },
            onError: () => {
                toast.error('Error al crear usuario');
            },
        });
    };

    const openEdit = (user: User) => {
        setSelectedUser(user);
        editForm.setData({
            name: user.name,
            email: user.email,
            password: '',
            password_confirmation: '',
            age: user.age?.toString() || '',
            gender: user.gender || '',
            country: user.country || '',
            entheogen_activity: user.entheogen_activity || '',
            role: user.primary_role,
        });
        setEditModalOpen(true);
    };

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

        editForm.put(update.url(selectedUser.id), {
            onSuccess: () => {
                setEditModalOpen(false);
                editForm.reset();
                toast.success('Usuario actualizado exitosamente');
            },
            onError: () => {
                toast.error('Error al actualizar usuario');
            },
        });
    };

    const openDelete = (user: User) => {
        setSelectedUser(user);
        setDeleteModalOpen(true);
    };

    const handleDelete = () => {
        if (!selectedUser) return;

        router.delete(destroy.url(selectedUser.id), {
            onSuccess: () => {
                setDeleteModalOpen(false);
                toast.success('Usuario eliminado exitosamente');
            },
            onError: () => {
                toast.error('Error al eliminar usuario');
            },
        });
    };

    const openRoleChange = (user: User) => {
        setSelectedUser(user);
        roleForm.setData({ role: user.primary_role });
        setRoleModalOpen(true);
    };

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

        roleForm.post(assignRole.url(selectedUser.id), {
            onSuccess: () => {
                setRoleModalOpen(false);
                roleForm.reset();
                toast.success('Rol actualizado exitosamente');
            },
            onError: () => {
                toast.error('Error al cambiar el rol');
            },
        });
    };

    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map(n => n[0])
            .join('')
            .toUpperCase()
            .slice(0, 2);
    };

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

            <div className="p-6 space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="p-3 rounded-2xl bg-forest/10">
                            <Users className="h-8 w-8 text-forest" />
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold">Gestión de Usuarios</h1>
                            <p className="text-muted-foreground">
                                {users.total} usuarios registrados
                            </p>
                        </div>
                    </div>
                    <Button onClick={() => setCreateModalOpen(true)} className="bg-forest hover:bg-forest-light">
                        <Plus className="mr-2 h-4 w-4" />
                        Nuevo Usuario
                    </Button>
                </div>

                {/* Filters */}
                <div className="flex gap-4">
                    <div className="relative flex-1">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                        <Input
                            placeholder="Buscar por nombre o email..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pl-10"
                        />
                    </div>
                    <Select value={roleFilter} onValueChange={setRoleFilter}>
                        <SelectTrigger className="w-[200px]">
                            <Filter className="mr-2 h-4 w-4" />
                            <SelectValue placeholder="Filtrar por rol" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">Todos los roles</SelectItem>
                            {roles.map((role) => (
                                <SelectItem key={role} value={role}>
                                    {role.charAt(0).toUpperCase() + role.slice(1)}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    {(searchTerm || roleFilter !== 'all') && (
                        <Button variant="outline" onClick={clearFilters}>
                            <X className="mr-2 h-4 w-4" />
                            Limpiar
                        </Button>
                    )}
                </div>

                {/* Table */}
                <div className="border rounded-lg">
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Usuario</TableHead>
                                <TableHead>Email</TableHead>
                                <TableHead>Rol</TableHead>
                                <TableHead>País</TableHead>
                                <TableHead>Registrado</TableHead>
                                <TableHead className="text-right">Acciones</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {users.data.map((user) => (
                                <TableRow key={user.id}>
                                    <TableCell>
                                        <div className="flex items-center gap-3">
                                            <Avatar>
                                                <AvatarFallback className="bg-forest/10 text-forest font-semibold">
                                                    {getInitials(user.name)}
                                                </AvatarFallback>
                                            </Avatar>
                                            <div>
                                                <div className="font-medium">{user.name}</div>
                                                {user.age && (
                                                    <div className="text-sm text-muted-foreground">
                                                        {user.age} años
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </TableCell>
                                    <TableCell>{user.email}</TableCell>
                                    <TableCell>
                                        <UserRoleBadge role={user.primary_role} />
                                    </TableCell>
                                    <TableCell>{user.country || '-'}</TableCell>
                                    <TableCell>
                                        <div className="text-sm">{user.created_at}</div>
                                        <div className="text-xs text-muted-foreground">
                                            {user.created_at_human}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" size="sm">
                                                    <MoreVertical className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuItem onClick={() => openEdit(user)}>
                                                    <Edit className="mr-2 h-4 w-4" />
                                                    Editar
                                                </DropdownMenuItem>
                                                <DropdownMenuItem onClick={() => openRoleChange(user)}>
                                                    <UserCog className="mr-2 h-4 w-4" />
                                                    Cambiar Rol
                                                </DropdownMenuItem>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem 
                                                    onClick={() => openDelete(user)}
                                                    className="text-destructive focus:text-destructive"
                                                >
                                                    <Trash2 className="mr-2 h-4 w-4" />
                                                    Eliminar
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>

                {/* Pagination */}
                {users.last_page > 1 && (
                    <div className="flex justify-center gap-2">
                        {Array.from({ length: users.last_page }, (_, i) => i + 1).map((page) => (
                            <Button
                                key={page}
                                variant={page === users.current_page ? 'default' : 'outline'}
                                size="sm"
                                onClick={() => router.get(index.url({ query: { page } }))}
                            >
                                {page}
                            </Button>
                        ))}
                    </div>
                )}
            </div>

            {/* Create Modal */}
            <Dialog open={createModalOpen} onOpenChange={setCreateModalOpen}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Crear Nuevo Usuario</DialogTitle>
                        <DialogDescription>
                            Completa los datos del nuevo usuario y asigna un rol.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleCreate} className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="create-name">Nombre *</Label>
                                <Input
                                    id="create-name"
                                    value={createForm.data.name}
                                    onChange={(e) => createForm.setData('name', e.target.value)}
                                    required
                                />
                                {createForm.errors.name && (
                                    <p className="text-sm text-destructive">{createForm.errors.name}</p>
                                )}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-email">Email *</Label>
                                <Input
                                    id="create-email"
                                    type="email"
                                    value={createForm.data.email}
                                    onChange={(e) => createForm.setData('email', e.target.value)}
                                    required
                                />
                                {createForm.errors.email && (
                                    <p className="text-sm text-destructive">{createForm.errors.email}</p>
                                )}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-password">Contraseña *</Label>
                                <Input
                                    id="create-password"
                                    type="password"
                                    value={createForm.data.password}
                                    onChange={(e) => createForm.setData('password', e.target.value)}
                                    required
                                />
                                {createForm.errors.password && (
                                    <p className="text-sm text-destructive">{createForm.errors.password}</p>
                                )}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-password-confirmation">Confirmar Contraseña *</Label>
                                <Input
                                    id="create-password-confirmation"
                                    type="password"
                                    value={createForm.data.password_confirmation}
                                    onChange={(e) => createForm.setData('password_confirmation', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-role">Rol *</Label>
                                <Select value={createForm.data.role} onValueChange={(value) => createForm.setData('role', value)}>
                                    <SelectTrigger id="create-role">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {roles.map((role) => (
                                            <SelectItem key={role} value={role}>
                                                {role.charAt(0).toUpperCase() + role.slice(1)}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                {createForm.errors.role && (
                                    <p className="text-sm text-destructive">{createForm.errors.role}</p>
                                )}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-age">Edad</Label>
                                <Input
                                    id="create-age"
                                    type="number"
                                    value={createForm.data.age}
                                    onChange={(e) => createForm.setData('age', e.target.value)}
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-gender">Género</Label>
                                <Select value={createForm.data.gender} onValueChange={(value) => createForm.setData('gender', value)}>
                                    <SelectTrigger id="create-gender">
                                        <SelectValue placeholder="Seleccionar" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="male">Masculino</SelectItem>
                                        <SelectItem value="female">Femenino</SelectItem>
                                        <SelectItem value="other">Otro</SelectItem>
                                        <SelectItem value="prefer_not_to_say">Prefiero no decir</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="create-country">País</Label>
                                <Input
                                    id="create-country"
                                    value={createForm.data.country}
                                    onChange={(e) => createForm.setData('country', e.target.value)}
                                />
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="create-entheogen">Actividad con enteógenos</Label>
                            <Textarea
                                id="create-entheogen"
                                value={createForm.data.entheogen_activity}
                                onChange={(e) => createForm.setData('entheogen_activity', e.target.value)}
                                rows={3}
                            />
                        </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 Usuario'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Edit Modal - Similar to Create Modal but with different form */}
            <Dialog open={editModalOpen} onOpenChange={setEditModalOpen}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Editar Usuario</DialogTitle>
                        <DialogDescription>
                            Modifica los datos del usuario. La contraseña es opcional.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleEdit} className="space-y-4">
                        {/* Similar structure to create form */}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="edit-name">Nombre *</Label>
                                <Input
                                    id="edit-name"
                                    value={editForm.data.name}
                                    onChange={(e) => editForm.setData('name', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="edit-email">Email *</Label>
                                <Input
                                    id="edit-email"
                                    type="email"
                                    value={editForm.data.email}
                                    onChange={(e) => editForm.setData('email', e.target.value)}
                                    required
                                />
                            </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 ? 'Guardando...' : 'Guardar Cambios'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Delete Confirmation Modal */}
            <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Confirmar Eliminación</DialogTitle>
                        <DialogDescription>
                            ¿Estás seguro de que deseas eliminar al usuario <strong>{selectedUser?.name}</strong>?
                            Esta acción no se puede deshacer.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setDeleteModalOpen(false)}>
                            Cancelar
                        </Button>
                        <Button variant="destructive" onClick={handleDelete}>
                            Eliminar Usuario
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Role Change Modal */}
            <Dialog open={roleModalOpen} onOpenChange={setRoleModalOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Cambiar Rol de Usuario</DialogTitle>
                        <DialogDescription>
                            Selecciona el nuevo rol para <strong>{selectedUser?.name}</strong>.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleRoleChange} className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="role-select">Rol</Label>
                            <Select value={roleForm.data.role} onValueChange={(value) => roleForm.setData('role', value)}>
                                <SelectTrigger id="role-select">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {roles.map((role) => (
                                        <SelectItem key={role} value={role}>
                                            {role.charAt(0).toUpperCase() + role.slice(1)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setRoleModalOpen(false)}>
                                Cancelar
                            </Button>
                            <Button type="submit" disabled={roleForm.processing} className="bg-forest hover:bg-forest-light">
                                {roleForm.processing ? 'Guardando...' : 'Cambiar Rol'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
