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, 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, CheckIcon } from 'lucide-react';
import { showLoading, updateToast } from '@/lib/toast';
import { useState, useEffect } from 'react';
import { cn } from '@/lib/utils';

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

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

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

interface User {
    id: number;
    name: string;
    email: string;
    phone?: string;
    description?: string;
    institution_id?: number;
    departamento_id?: number;
    municipio_id?: number;
    profile_completed: boolean;
    is_researcher: boolean;
}

interface Props {
    user: User;
    institutions: Institution[];
}

export default function UsersEdit({ user, institutions }: Props) {
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Dashboard', href: '/dashboard' },
        { title: 'Usuarios', href: '/users' },
        { title: user.name, href: `/users/${user.id}` },
        { title: 'Editar', href: `/users/${user.id}/edit` },
    ];

    const { data, setData, put, processing, errors } = useForm({
        name: user.name || '',
        email: user.email || '',
        phone: user.phone || '',
        password: '',
        password_confirmation: '',
        description: user.description || '',
        institution_id: user.institution_id?.toString() || '',
        departamento_id: user.departamento_id?.toString() || '',
        municipio_id: user.municipio_id?.toString() || '',
        profile_completed: user.profile_completed as boolean,
        is_researcher: user.is_researcher as boolean,
    });

    const [departamentos, setDepartamentos] = useState<Departamento[]>([]);
    const [municipios, setMunicipios] = useState<Municipio[]>([]);
    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));
        } else {
            setMunicipios([]);
        }
    }, [data.departamento_id, setData]);

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

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

        put(`/users/${user.id}`, {
            onSuccess: () => {
                updateToast(toastId, 'success', 'Usuario actualizado exitosamente');
            },
            onError: () => {
                updateToast(toastId, 'error', 'Error al actualizar el usuario');
            }
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Editar Usuario - ${user.name}`} />

            <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">
                                    Editar Usuario
                                </h1>
                                <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm">
                                    Actualiza la información de {user.name}
                                </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>
                                Actualiza los datos del 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-2 gap-6">
                                    {/* Contraseña */}
                                    <div className="space-y-2">
                                        <label htmlFor="password" className="text-sm font-medium text-slate-900 dark:text-white">
                                            Nueva contraseña
                                        </label>
                                        <Input
                                            id="password"
                                            type="password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="Deja en blanco para mantener la actual"
                                            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 nueva contraseña
                                        </label>
                                        <Input
                                            id="password_confirmation"
                                            type="password"
                                            value={data.password_confirmation}
                                            onChange={(e) => setData('password_confirmation', e.target.value)}
                                            placeholder="Confirma la nueva 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>


                                <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>
                                        <Select value={data.institution_id === '' ? 'none' : data.institution_id} onValueChange={(value) => {
                                            if (value === "none") {
                                                setData('institution_id', '');
                                            } else {
                                                setData('institution_id', value);
                                            }
                                        }}>
                                            <SelectTrigger className={errors.institution_id ? 'border-red-500' : ''}>
                                                <SelectValue placeholder="Selecciona una institución" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="none">Sin institución</SelectItem>
                                                {institutions.map((institution) => (
                                                    <SelectItem key={institution.id} value={institution.id.toString()}>
                                                        {institution.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        {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((departamento) => departamento.id.toString() === data.departamento_id)?.name
                                                        : "Selecciona un departamento"}
                                                    <CheckIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="w-full p-0" side="bottom">
                                                <Command>
                                                    <CommandInput placeholder="Buscar departamento..." />
                                                    <CommandEmpty>No se encontraron departamentos.</CommandEmpty>
                                                    <CommandGroup>
                                                        {departamentos.map((departamento) => (
                                                            <CommandItem
                                                                key={departamento.id}
                                                                value={departamento.name}
                                                                onSelect={() => {
                                                                    setData('departamento_id', departamento.id.toString());
                                                                    setData('municipio_id', '');
                                                                    setDepartamentoOpen(false);
                                                                }}
                                                            >
                                                                <CheckIcon
                                                                    className={`mr-2 h-4 w-4 ${data.departamento_id === departamento.id.toString() ? "opacity-100" : "opacity-0"
                                                                        }`}
                                                                />
                                                                {departamento.name}
                                                            </CommandItem>
                                                        ))}
                                                    </CommandGroup>
                                                </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((municipio) => municipio.id.toString() === data.municipio_id)?.name
                                                        : "Selecciona un municipio"}
                                                    <CheckIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="w-full p-0" side="bottom">
                                                <Command>
                                                    <CommandInput placeholder="Buscar municipio..." />
                                                    <CommandEmpty>No se encontraron municipios.</CommandEmpty>
                                                    <CommandGroup>
                                                        {municipios.map((municipio) => (
                                                            <CommandItem
                                                                key={municipio.id}
                                                                value={municipio.name}
                                                                onSelect={() => {
                                                                    setData('municipio_id', municipio.id.toString());
                                                                    setMunicipioOpen(false);
                                                                }}
                                                            >
                                                                <CheckIcon
                                                                    className={`mr-2 h-4 w-4 ${data.municipio_id === municipio.id.toString() ? "opacity-100" : "opacity-0"
                                                                        }`}
                                                                />
                                                                {municipio.name}
                                                            </CommandItem>
                                                        ))}
                                                    </CommandGroup>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        {errors.municipio_id && (
                                            <p className="text-sm text-red-600 dark:text-red-400">
                                                {errors.municipio_id}
                                            </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...' : 'Actualizar Usuario'}
                                    </Button>
                                    <Button variant="outline" asChild>
                                        <Link href="/users">
                                            Cancelar
                                        </Link>
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AppLayout>
    );
}