import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandList, CommandItem } from '@/components/ui/command';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Save, Users, ChevronsUpDown } from 'lucide-react';
import { showLoading, updateToast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import { useState, useEffect } from 'react';

interface Institution {
    id: number;
    name: string;
}

type Departamento = {
    id: number;
    name: string;
    code: string;
};

type Municipio = {
    id: number;
    name: string;
    code: string;
};

interface Props {
    institutions: Institution[];
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Usuarios', href: '/users' },
    { title: 'Nuevo Usuario', href: '/users/create' },
];

export default function UsersCreate({ institutions }: Props) {
    const { data, setData, post, processing, errors } = useForm({
        name: '',
        email: '',
        phone: '',
        password: '',
        password_confirmation: '',
        description: '',
        institution_id: '',
        departamento_id: '',
        municipio_id: '',
        profile_completed: false as boolean,
        is_researcher: false as boolean,
    });

    const [departamentos, setDepartamentos] = useState<Departamento[]>([]);
    const [municipios, setMunicipios] = useState<Municipio[]>([]);
    const [institutionOpen, setInstitutionOpen] = useState(false);
    const [departamentoOpen, setDepartamentoOpen] = useState(false);
    const [municipioOpen, setMunicipioOpen] = useState(false);

    // Fetch departments on component mount
    useEffect(() => {
        fetch('/api/departamentos')
            .then(response => response.json())
            .then(data => setDepartamentos(data))
            .catch(error => console.error('Error fetching departments:', error));
    }, []);

    // Fetch municipalities when department changes
    useEffect(() => {
        if (data.departamento_id) {
            fetch(`/api/municipios/${data.departamento_id}`)
                .then(response => response.json())
                .then(data => setMunicipios(data))
                .catch(error => console.error('Error fetching municipalities:', error));
            // Reset municipio when departamento changes
            setData('municipio_id', '');
        } else {
            setMunicipios([]);
        }
    }, [data.departamento_id, setData]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const toastId = showLoading('Creando usuario...');

        post('/users', {
            onSuccess: () => {
                updateToast(toastId, 'success', 'Usuario creado exitosamente');
            },
            onError: () => {
                updateToast(toastId, 'error', 'Error al crear el usuario');
            }
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Nuevo Usuario" />

            <div className="flex h-full flex-1 flex-col gap-6 rounded-xl p-6">
                {/* Header */}
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-start gap-3 flex-1">
                            <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg flex-shrink-0">
                                <Users className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
                            </div>
                            <div className="min-w-0 flex-1">
                                <h1 className="text-xl font-bold text-slate-900 dark:text-white sm:text-2xl">
                                    Nuevo Usuario
                                </h1>
                                <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm">
                                    Crea un nuevo usuario en el sistema
                                </p>
                            </div>
                        </div>
                        <Button variant="outline" asChild className="ml-4 flex-shrink-0">
                            <Link href="/users">
                                <ArrowLeft className="w-4 h-4 mr-2" />
                                Volver
                            </Link>
                        </Button>
                    </div>
                </div>

                {/* Form */}
                <div className="w-full max-w-5xl mx-auto">
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                Información del Usuario
                            </CardTitle>
                            <CardDescription>
                                Completa los datos para crear el nuevo usuario
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <form onSubmit={handleSubmit} className="space-y-6">
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                    {/* Nombre */}
                                    <div className="space-y-2">
                                        <label htmlFor="name" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Nombre completo *
                                        </label>
                                        <Input
                                            id="name"
                                            type="text"
                                            value={data.name}
                                            onChange={(e) => setData('name', e.target.value)}
                                            placeholder="Ingresa el nombre completo"
                                            className={errors.name ? 'border-red-500' : ''}
                                        />
                                        {errors.name && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.name}
                                            </p>
                                        )}
                                    </div>

                                    {/* Email */}
                                    <div className="space-y-2">
                                        <label htmlFor="email" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Correo electrónico *
                                        </label>
                                        <Input
                                            id="email"
                                            type="email"
                                            value={data.email}
                                            onChange={(e) => setData('email', e.target.value)}
                                            placeholder="usuario@ejemplo.com"
                                            className={errors.email ? 'border-red-500' : ''}
                                        />
                                        {errors.email && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.email}
                                            </p>
                                        )}
                                    </div>

                                    {/* Teléfono */}
                                    <div className="space-y-2">
                                        <label htmlFor="phone" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Teléfono *
                                        </label>
                                        <Input
                                            id="phone"
                                            type="number"
                                            value={data.phone}
                                            onChange={(e) => setData('phone', e.target.value)}
                                            placeholder="(+57) 3xx xxx xxxx"
                                            className={errors.phone ? 'border-red-500' : ''}
                                        />
                                        {errors.phone && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.phone}
                                            </p>
                                        )}
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                    {/* Institución */}
                                    <div className="space-y-2">
                                        <label htmlFor="institution_id" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Institución
                                        </label>
                                        <Popover open={institutionOpen} onOpenChange={setInstitutionOpen}>
                                            <PopoverTrigger asChild>
                                                <Button
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={institutionOpen}
                                                    className={cn(
                                                        "w-full justify-between",
                                                        data.institution_id ? "text-slate-900 dark:text-slate-50 dark:hover:text-slate-50 hover:text-slate-900 hover:bg-white border border-slate-300 dark:border-slate-700" : "text-slate-400 dark:text-slate-500 dark:hover:text-slate-50 hover:text-slate-500 hover:bg-white border border-slate-300 dark:border-slate-700",
                                                        errors.institution_id ? 'border-red-500' : ''
                                                    )}
                                                    disabled={processing}
                                                >
                                                    {data.institution_id
                                                        ? institutions.find((inst) => inst.id.toString() === data.institution_id)?.name
                                                        : "Selecciona una institución..."}
                                                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="w-full p-0">
                                                <Command>
                                                    <CommandInput placeholder="Buscar institución..." />
                                                    <CommandList className="text-gray-100">
                                                        <CommandEmpty>No se encontró institución.</CommandEmpty>
                                                        <CommandGroup>
                                                            <CommandItem
                                                                value="sin-institucion"
                                                                onSelect={() => {
                                                                    setData('institution_id', '');
                                                                    setInstitutionOpen(false);
                                                                }}
                                                            >
                                                                Sin institución
                                                            </CommandItem>
                                                            {institutions.map((institution) => (
                                                                <CommandItem
                                                                    key={institution.id}
                                                                    value={institution.name}
                                                                    onSelect={() => {
                                                                        setData('institution_id', institution.id.toString());
                                                                        setInstitutionOpen(false);
                                                                    }}
                                                                >
                                                                    {institution.name}
                                                                </CommandItem>
                                                            ))}
                                                        </CommandGroup>
                                                    </CommandList>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        {errors.institution_id && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.institution_id}
                                            </p>
                                        )}
                                    </div>

                                    {/* Departamento */}
                                    <div className="space-y-2">
                                        <label htmlFor="departamento" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Departamento
                                        </label>
                                        <Popover open={departamentoOpen} onOpenChange={setDepartamentoOpen}>
                                            <PopoverTrigger asChild>
                                                <Button
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={departamentoOpen}
                                                    className={cn(
                                                        "w-full justify-between",
                                                        data.departamento_id ? "text-slate-900 dark:text-slate-50 dark:hover:text-slate-50 hover:text-slate-900 hover:bg-white border border-slate-300 dark:border-slate-700" : "text-slate-400 dark:text-slate-500 dark:hover:text-slate-50 hover:text-slate-500 hover:bg-white border border-slate-300 dark:border-slate-700"
                                                    )}
                                                    disabled={processing}
                                                >
                                                    {data.departamento_id
                                                        ? departamentos.find((dep) => dep.id.toString() === data.departamento_id)?.name
                                                        : "Selecciona un departamento..."}
                                                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="w-full p-0">
                                                <Command>
                                                    <CommandInput placeholder="Buscar departamento..." />
                                                    <CommandList className="text-gray-100">
                                                        <CommandEmpty>No se encontró departamento.</CommandEmpty>
                                                        <CommandGroup>
                                                            {departamentos.map((departamento) => (
                                                                <CommandItem
                                                                    key={departamento.id}
                                                                    value={departamento.name}
                                                                    onSelect={() => {
                                                                        setData('departamento_id', departamento.id.toString());
                                                                        setDepartamentoOpen(false);
                                                                    }}
                                                                >
                                                                    {departamento.name}
                                                                </CommandItem>
                                                            ))}
                                                        </CommandGroup>
                                                    </CommandList>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        {errors.departamento_id && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.departamento_id}
                                            </p>
                                        )}
                                    </div>

                                    {/* Municipio */}
                                    <div className="space-y-2">
                                        <label htmlFor="municipio" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Municipio
                                        </label>
                                        <Popover open={municipioOpen} onOpenChange={setMunicipioOpen}>
                                            <PopoverTrigger asChild>
                                                <Button
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={municipioOpen}
                                                    className={cn(
                                                        "w-full justify-between",
                                                        data.departamento_id ? "text-slate-900 dark:text-slate-50 dark:hover:text-slate-50 hover:text-slate-900 hover:bg-white border border-slate-300 dark:border-slate-700" : "text-slate-400 dark:text-slate-500 dark:hover:text-slate-50 hover:text-slate-500 hover:bg-white border border-slate-300 dark:border-slate-700"
                                                    )}
                                                    disabled={processing || !data.departamento_id}
                                                >
                                                    {data.municipio_id
                                                        ? municipios.find((mun) => mun.id.toString() === data.municipio_id)?.name
                                                        : "Selecciona un municipio..."}
                                                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="w-full p-0">
                                                <Command>
                                                    <CommandInput placeholder="Buscar municipio..." />
                                                    <CommandList>
                                                        <CommandEmpty>No se encontró municipio.</CommandEmpty>
                                                        <CommandGroup>
                                                            {municipios.map((municipio) => (
                                                                <CommandItem
                                                                    key={municipio.id}
                                                                    value={municipio.name}
                                                                    onSelect={() => {
                                                                        setData('municipio_id', municipio.id.toString());
                                                                        setMunicipioOpen(false);
                                                                    }}
                                                                >
                                                                    {municipio.name}
                                                                </CommandItem>
                                                            ))}
                                                        </CommandGroup>
                                                    </CommandList>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        {errors.municipio_id && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.municipio_id}
                                            </p>
                                        )}
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    {/* Contraseña */}
                                    <div className="space-y-2">
                                        <label htmlFor="password" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Contraseña *
                                        </label>
                                        <Input
                                            id="password"
                                            type="password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="Ingresa una contraseña segura"
                                            className={errors.password ? 'border-red-500' : ''}
                                        />
                                        {errors.password && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.password}
                                            </p>
                                        )}
                                    </div>

                                    {/* Confirmar contraseña */}
                                    <div className="space-y-2">
                                        <label htmlFor="password_confirmation" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Confirmar contraseña *
                                        </label>
                                        <Input
                                            id="password_confirmation"
                                            type="password"
                                            value={data.password_confirmation}
                                            onChange={(e) => setData('password_confirmation', e.target.value)}
                                            placeholder="Confirma la contraseña"
                                            className={errors.password_confirmation ? 'border-red-500' : ''}
                                        />
                                        {errors.password_confirmation && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.password_confirmation}
                                            </p>
                                        )}
                                    </div>
                                </div>

                                {/* Descripción */}
                                <div className="space-y-2">
                                    <label htmlFor="description" className="text-sm font-medium text-slate-900 dark:text-white">
                                        Descripción
                                    </label>
                                    <Textarea
                                        id="description"
                                        value={data.description}
                                        onChange={(e) => setData('description', e.target.value)}
                                        placeholder="Describe brevemente al usuario (opcional)"
                                        rows={4}
                                        className={errors.description ? 'border-red-500' : ''}
                                    />
                                    {errors.description && (
                                        <p className="text-sm text-red-600 dark:text-red-400">
                                            {errors.description}
                                        </p>
                                    )}
                                </div>

                                <div className="flex flex-wrap gap-6">
                                    {/* Perfil completado */}
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="profile_completed"
                                            checked={data.profile_completed}
                                            onCheckedChange={(checked: boolean) => setData('profile_completed', checked)}
                                        />
                                        <Label htmlFor="profile_completed" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Marcar perfil como completado
                                        </Label>
                                    </div>

                                    {/* Es investigador */}
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="is_researcher"
                                            checked={data.is_researcher}
                                            onCheckedChange={(checked: boolean) => setData('is_researcher', checked)}
                                        />
                                        <Label htmlFor="is_researcher" className="text-sm font-medium text-slate-900 dark:text-white">
                                            ¿Es investigador?
                                        </Label>
                                    </div>
                                </div>

                                <div className="flex gap-3 pt-4">
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        className="bg-emerald-600 hover:bg-emerald-700"
                                    >
                                        <Save className="w-4 h-4 mr-2" />
                                        {processing ? 'Guardando...' : 'Guardar Usuario'}
                                    </Button>
                                    <Button variant="outline" asChild>
                                        <Link href="/users">
                                            Cancelar
                                        </Link>
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AppLayout>
    );
}