import clsx from 'clsx';
import { Check, ChevronDown, Search } from 'lucide-react';
import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

export type OpcionBuscable = { value: string; label: string; detalle?: string };

/**
 * Select de formulario con buscador (a todo el ancho, con la etiqueta fuera).
 * Filtra al escribir sin distinguir acentos ni mayúsculas; Enter elige la primera coincidencia y Esc cierra.
 * Para filtros de barra (etiqueta dentro y "Todos") usar FilterSelect de components/dashboard.
 */
export function SelectBuscable({
    value,
    onChange,
    options,
    placeholder = 'Seleccionar…',
    buscarPlaceholder = 'Buscar…',
    id,
    disabled,
}: {
    value: string;
    onChange: (v: string) => void;
    options: OpcionBuscable[];
    placeholder?: string;
    buscarPlaceholder?: string;
    id?: string;
    disabled?: boolean;
}) {
    const [abierto, setAbierto] = useState(false);
    const [q, setQ] = useState('');
    const norm = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
    const filtradas = q.trim() === '' ? options : options.filter((o) => norm(`${o.label} ${o.detalle ?? ''}`).includes(norm(q.trim())));
    const actual = options.find((o) => o.value === value);

    const elegir = (v: string) => {
        setAbierto(false);
        setQ('');
        if (v !== value) onChange(v);
    };

    return (
        <Popover
            open={abierto}
            onOpenChange={(o) => {
                setAbierto(o);
                if (!o) setQ('');
            }}
        >
            <PopoverTrigger
                id={id}
                disabled={disabled}
                className="flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 text-left text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=open]:border-ring"
            >
                <span className={clsx('min-w-0 truncate', !actual && 'text-muted-foreground')}>
                    {actual ? (
                        <>
                            {actual.label}
                            {actual.detalle && <span className="text-muted-foreground"> · {actual.detalle}</span>}
                        </>
                    ) : (
                        placeholder
                    )}
                </span>
                <ChevronDown className="size-4 shrink-0 text-muted-foreground" />
            </PopoverTrigger>
            <PopoverContent align="start" className="w-(--radix-popover-trigger-width) min-w-64 p-2">
                <div className="relative mb-2">
                    <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
                    <Input
                        autoFocus
                        value={q}
                        onChange={(e) => setQ(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter' && filtradas[0]) {
                                e.preventDefault();
                                elegir(filtradas[0].value);
                            }
                        }}
                        placeholder={buscarPlaceholder}
                        className="h-8 pl-8 text-sm"
                    />
                </div>
                <div className="max-h-64 overflow-y-auto" role="listbox">
                    {filtradas.map((o) => (
                        <button
                            key={o.value}
                            type="button"
                            role="option"
                            aria-selected={o.value === value}
                            onClick={() => elegir(o.value)}
                            className={clsx('flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted', o.value === value && 'font-semibold')}
                        >
                            <Check className={clsx('size-3.5 shrink-0', o.value === value ? 'opacity-100' : 'opacity-0')} />
                            <span className="min-w-0 truncate">
                                {o.label}
                                {o.detalle && <span className="font-normal text-muted-foreground"> · {o.detalle}</span>}
                            </span>
                        </button>
                    ))}
                    {filtradas.length === 0 && <p className="px-2 py-3 text-center text-xs text-muted-foreground">Sin resultados</p>}
                </div>
            </PopoverContent>
        </Popover>
    );
}
