import { useHttp } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { index as brigadistasIndex, store as brigadistasStore } from '@/routes/brigadistas';
import { useCatalogo } from '../hooks/use-catalogo';

type Brigadista = { id: number; nombre: string };

export function BrigadistaCombobox({
    value,
    onChange,
    error,
}: {
    value: number | null;
    onChange: (value: number | null) => void;
    error?: string;
}) {
    const { data: catalog, loading } = useCatalogo<Brigadista[]>(brigadistasIndex.url());
    const [created, setCreated] = useState<Brigadista[]>([]);
    const [dialogOpen, setDialogOpen] = useState(false);
    const httpPost = useHttp<{ nombre: string }>({ nombre: '' });

    const options = useMemo(() => {
        const merged = [...(catalog ?? []), ...created];
        const seen = new Set<number>();
        return merged.filter((item) => {
            if (seen.has(item.id)) {
                return false;
            }
            seen.add(item.id);
            return true;
        });
    }, [catalog, created]);

    const selectedItem = value != null
        ? (options.find((item) => item.id === value) ?? null)
        : null;

    const handleOpenDialog = () => {
        httpPost.setData('nombre', '');
        setDialogOpen(true);
    };

    const handleSave = () => {
        const trimmed = httpPost.data.nombre.trim();
        if (!trimmed) {
            toast.error('El nombre del brigadista es obligatorio');
            return;
        }

        httpPost.post(brigadistasStore.url(), {
            onSuccess: (response: unknown) => {
                const data = response as Brigadista | undefined;
                if (!data || typeof data.id !== 'number' || typeof data.nombre !== 'string') {
                    toast.error('Respuesta inesperada del servidor');
                    return;
                }
                setCreated((prev) => [...prev, data]);
                onChange(data.id);
                setDialogOpen(false);
                toast.success('Brigadista creado correctamente');
            },
            onError: (errors: unknown) => {
                const msgs = errors as Record<string, string[]>;
                const first = Object.values(msgs).flat()[0];
                toast.error(first ?? 'No se pudo crear el brigadista');
            },
        });
    };

    return (
        <div className="flex flex-col gap-1">
            <Combobox<Brigadista>
                value={selectedItem}
                onValueChange={(item) => {
                    const v = item as Brigadista | null;
                    onChange(v ? v.id : null);
                }}
                items={options}
                isItemEqualToValue={(a, b) => a?.id === b?.id}
                itemToStringLabel={(b: Brigadista) => b.nombre}
            >
                <ComboboxInput
                    className="w-full!"
                    placeholder={loading ? 'Cargando…' : 'Seleccionar brigadista'}
                    showTrigger
                />
                <ComboboxContent>
                    <ComboboxList>
                        {options.map((item) => (
                            <ComboboxItem key={item.id} value={item}>
                                {item.nombre}
                            </ComboboxItem>
                        ))}
                    </ComboboxList>
                    <ComboboxEmpty>Sin resultados</ComboboxEmpty>
                </ComboboxContent>
            </Combobox>

            <Button
                type="button"
                variant="outline"
                size="sm"
                className="w-fit"
                onClick={handleOpenDialog}
            >
                <Plus data-icon="inline-start" />
                Crear brigadista
            </Button>

            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Añadir brigadista</DialogTitle>
                        <DialogDescription>
                            Ingrese el nombre completo del nuevo brigadista.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="py-4">
                        <Input
                            placeholder="Nombre del brigadista"
                            value={httpPost.data.nombre}
                            onChange={(e) => httpPost.setData('nombre', e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    e.preventDefault();
                                    handleSave();
                                }
                            }}
                            autoFocus
                        />
                    </div>
                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => setDialogOpen(false)}
                            disabled={httpPost.processing}
                        >
                            Cancelar
                        </Button>
                        <Button
                            type="button"
                            onClick={handleSave}
                            disabled={httpPost.processing || !httpPost.data.nombre.trim()}
                        >
                            {httpPost.processing ? 'Guardando…' : 'Guardar'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {error ? (
                <span className="text-xs text-destructive">{error}</span>
            ) : null}
        </div>
    );
}
