import { Head, useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler, useState, useEffect } from 'react';
import { CheckIcon, ChevronsUpDownIcon } from 'lucide-react';

import InputError from '@/components/input-error';
import TextLink from '@/components/text-link';
import { Button } from '@/components/ui/button';
import PrimaryButton from '@/components/landing/primary-button';
import GoogleIcon from '@/components/icons/google-icon';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import NeuralBackground from '@/components/landing/neural-background';
import AIParticles from '@/components/landing/ai-particles';
import Container from '@/components/landing/container';
import AppLogoIcon from '@/components/app-logo-icon';
import ThemeToggle from '@/components/theme-toggle';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';

type RegisterForm = {
    name: string;
    email: string;
    phone: string;
    password: string;
    password_confirmation: string;
    departamento_id: string;
    municipio_id: string;
};

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

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

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

interface Props {
    institutions: Institution[];
}

export default function Register({ institutions }: Props) {
    const { data, setData, post, processing, errors, reset } = useForm<Required<RegisterForm>>({
        name: '',
        email: '',
        phone: '',
        password: '',
        password_confirmation: '',
        departamento_id: '',
        municipio_id: '',
    });

    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));
            // Reset municipio when departamento changes
            setData('municipio_id', '');
        } else {
            setMunicipios([]);
        }
    }, [data.departamento_id, setData]);

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('register'), {
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

    const inputClass =
        "w-full h-10 rounded-xl border border-slate-300 dark:border-slate-700 bg-transparent text-sm px-3 focus:outline-none focus:ring-2 focus:ring-[#00d492] focus:border-[#00d492] transition-all placeholder:text-slate-400 dark:placeholder:text-slate-500";


    return (
        <>
            <Head title="Register" />
            <div className="relative min-h-screen flex items-center justify-center overflow-hidden bg-gradient-to-br from-slate-50 via-purple-50 to-slate-50 dark:from-slate-900 dark:via-purple-900 dark:to-slate-900">
                {/* Toggle de tema flotante */}
                <div className="fixed top-4 left-4 z-50">
                    <ThemeToggle />
                </div>
                <NeuralBackground />
                <AIParticles density={30} />
                <Container className="relative z-10 flex flex-col items-center justify-center min-h-screen py-12">
                    <div className="w-full max-w-4xl mx-auto bg-white/90 dark:bg-slate-900/80 rounded-3xl shadow-2xl border border-slate-200 dark:border-slate-800/60 backdrop-blur-md p-8 sm:p-10 flex flex-col gap-8">
                        <div className="flex flex-col items-center gap-3">
                            <AppLogoIcon />
                            <h1 className="text-2xl font-extrabold dark:text-white text-black">Crear cuenta</h1>
                            <p className="text-sm text-slate-500 dark:text-slate-300 text-center">Ingresa tus datos para crear tu cuenta</p>
                        </div>
                        <div className="flex flex-col gap-6">
                            {/* Google Register Button */}
                            <PrimaryButton
                                className="w-full flex items-center justify-center gap-3 bg-white text-slate-900 border border-slate-200 hover:bg-slate-50 shadow-md rounded-2xl font-semibold text-base py-3 mb-2"
                                href={route('auth.google')}
                            >
                                <GoogleIcon className="w-6 h-6" />
                                <span>Registrarse con Google</span>
                            </PrimaryButton>
                            <div className="relative flex items-center py-2">
                                <div className="flex-grow border-t border-slate-200 dark:border-slate-700" />
                                <span className="mx-4 text-xs text-slate-400 dark:text-slate-500">o</span>
                                <div className="flex-grow border-t border-slate-200 dark:border-slate-700" />
                            </div>
                            <form className="flex flex-col space-y-2 gap-6" onSubmit={submit}>
                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">

                                    <div className="grid gap-2">
                                        <Label htmlFor="name">Investigador(a/es)</Label>
                                        <Input
                                            id="name"
                                            type="text"
                                            required
                                            autoFocus
                                            tabIndex={1}
                                            autoComplete="name"
                                            value={data.name}
                                            onChange={(e) => setData('name', e.target.value)}
                                            disabled={processing}
                                            placeholder="Nombre(s) y Apellido(s)"
                                        />
                                        <InputError message={errors.name} className="mt-2" />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="email">Correo institucional</Label>
                                        <Input
                                            id="email"
                                            type="email"
                                            required
                                            tabIndex={2}
                                            autoComplete="email"
                                            value={data.email}
                                            onChange={(e) => setData('email', e.target.value)}
                                            disabled={processing}
                                            placeholder="nombre@institucion.edu"
                                        />
                                        <InputError message={errors.email} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="phone">Teléfono</Label>
                                        <Input
                                            id="phone"
                                            type="number"
                                            required
                                            tabIndex={3}
                                            autoComplete="tel"
                                            value={data.phone}
                                            onChange={(e) => setData('phone', e.target.value)}
                                            disabled={processing}
                                            placeholder="(+57) 3xx xxx xxxx"
                                        />
                                        <InputError message={errors.phone} className="mt-2" />
                                    </div>
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="grid gap-2">
                                        <Label htmlFor="departamento">Departamento</Label>
                                        <Popover open={departamentoOpen} onOpenChange={setDepartamentoOpen}>
                                            <PopoverTrigger asChild>
                                                <Button
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={departamentoOpen}
                                                    className={cn(
                                                        inputClass,
                                                        "justify-between",
                                                        data.departamento_id ? "text-slate-900 dark:text-slate-50 dark:hover:text-slate-50 hover:text-slate-900 hover:bg-white" : "text-slate-400 dark:text-slate-500 hover:text-slate-400 dark:hover:text-slate-500 hover:bg-white"
                                                    )}
                                                    disabled={processing}
                                                >
                                                    {data.departamento_id
                                                        ? departamentos.find((dep) => dep.id.toString() === data.departamento_id)?.name
                                                        : "Selecciona un departamento..."}
                                                    <ChevronsUpDownIcon 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);
                                                                    }}
                                                                >
                                                                    <CheckIcon
                                                                        className={cn(
                                                                            "mr-2 h-4 w-4",
                                                                            data.departamento_id === departamento.id.toString() ? "opacity-100" : "opacity-0"
                                                                        )}
                                                                    />
                                                                    {departamento.name}
                                                                </CommandItem>
                                                            ))}
                                                        </CommandGroup>
                                                    </CommandList>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        <InputError message={errors.departamento_id} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="municipio">Municipio</Label>
                                        <Popover open={municipioOpen} onOpenChange={setMunicipioOpen}>
                                            <PopoverTrigger asChild>
                                                <Button
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={municipioOpen}
                                                    className={cn(
                                                        inputClass,
                                                        "justify-between",
                                                        data.departamento_id ? "text-slate-900 dark:text-slate-50 dark:hover:text-slate-50 hover:text-slate-900 hover:bg-white" : "text-slate-400 dark:text-slate-500"
                                                    )}
                                                    disabled={processing || !data.departamento_id}
                                                >
                                                    {data.municipio_id
                                                        ? municipios.find((mun) => mun.id.toString() === data.municipio_id)?.name
                                                        : "Selecciona un municipio..."}
                                                    <ChevronsUpDownIcon 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);
                                                                    }}
                                                                >
                                                                    <CheckIcon
                                                                        className={cn(
                                                                            "mr-2 h-4 w-4",
                                                                            data.municipio_id === municipio.id.toString() ? "opacity-100" : "opacity-0"
                                                                        )}
                                                                    />
                                                                    {municipio.name}
                                                                </CommandItem>
                                                            ))}
                                                        </CommandGroup>
                                                    </CommandList>
                                                </Command>
                                            </PopoverContent>
                                        </Popover>
                                        <InputError message={errors.municipio_id} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="grid gap-2">
                                        <Label htmlFor="password">Contraseña</Label>
                                        <Input
                                            id="password"
                                            type="password"
                                            required
                                            tabIndex={3}
                                            autoComplete="new-password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            disabled={processing}
                                            placeholder="Contraseña"
                                        />
                                        <InputError message={errors.password} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="password_confirmation">Confirmar contraseña</Label>
                                        <Input
                                            id="password_confirmation"
                                            type="password"
                                            required
                                            tabIndex={4}
                                            autoComplete="new-password"
                                            value={data.password_confirmation}
                                            onChange={(e) => setData('password_confirmation', e.target.value)}
                                            disabled={processing}
                                            placeholder="Confirmar contraseña"
                                        />
                                        <InputError message={errors.password_confirmation} />
                                    </div>
                                </div>

                                <Button type="submit" className="mt-2 w-full bg-emerald-600 text-white font-bold rounded-2xl shadow-lg hover:scale-105 transition-all duration-300 border-none sm:col-span-2" tabIndex={5} disabled={processing}>
                                    {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                    Crear cuenta
                                </Button>

                                <div className="text-center text-sm text-muted-foreground">
                                    ¿Ya tienes cuenta?{' '}
                                    <TextLink href={route('login')} tabIndex={6}>
                                        Inicia sesión
                                    </TextLink>
                                </div>
                            </form>
                        </div>
                    </div >
                </Container >
            </div >
        </>
    );
}
