import { useEffect, useMemo, useRef, useState } from 'react';
import { COUNTRIES, findCountry, type Country } from '@/lib/locales';

// Searchable country combobox. Mirrors wedding's CountryCombobox:
//   - Type to filter; matches on display name or ISO code.
//   - onMouseDown selection (fires before blur, so the picked option survives).
//   - Outside-click restores the last confirmed value (no stuck partial input).
//   - ChevronDown icon to telegraph the dropdown.
//
// The form holds the ISO-2 code as the value; the input shows the display name.

export function CountryCombobox({
    value,
    onChange,
    placeholder = 'Select a country',
    className,
}: {
    value: string;                          // ISO-2 code (or '')
    onChange: (code: string) => void;       // emits ISO-2 code
    placeholder?: string;
    className?: string;
}) {
    const current = findCountry(value);
    const [query, setQuery] = useState<string>(current?.name ?? '');
    const [open, setOpen] = useState(false);
    const inputRef = useRef<HTMLInputElement>(null);
    const wrapRef = useRef<HTMLDivElement>(null);

    // Keep the input in sync when value changes from outside (e.g. form reset).
    useEffect(() => {
        const next = findCountry(value)?.name ?? '';
        setQuery(next);
    }, [value]);

    // Outside-click → close + restore last confirmed value.
    useEffect(() => {
        function onDown(e: MouseEvent) {
            if (!wrapRef.current?.contains(e.target as Node)) {
                setOpen(false);
                setQuery(findCountry(value)?.name ?? '');
            }
        }
        if (open) document.addEventListener('mousedown', onDown);
        return () => document.removeEventListener('mousedown', onDown);
    }, [open, value]);

    const filtered = useMemo<Country[]>(() => {
        const q = query.trim().toLowerCase();
        if (!q) return COUNTRIES;
        return COUNTRIES.filter(
            (c) =>
                c.name.toLowerCase().includes(q) ||
                c.code.toLowerCase().startsWith(q),
        );
    }, [query]);

    function pick(c: Country) {
        onChange(c.code);
        setQuery(c.name);
        setOpen(false);
        inputRef.current?.blur();
    }

    return (
        <div ref={wrapRef} className={`relative ${className ?? ''}`}>
            <input
                ref={inputRef}
                type="text"
                value={query}
                onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
                onFocus={() => setOpen(true)}
                placeholder={placeholder}
                autoComplete="off"
                className="input pr-9"
            />
            <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-foreground/40">
                <svg className="w-4 h-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                    <path d="m4 6 4 4 4-4" />
                </svg>
            </span>

            {open && (
                <div className="absolute z-40 mt-1.5 left-0 right-0 max-h-[280px] overflow-y-auto bg-card border border-border rounded-xl shadow-[0_18px_40px_-15px_rgba(0,0,0,0.18)]">
                    {filtered.length === 0 ? (
                        <p className="px-3 py-3 text-[12.5px] text-muted-foreground">No matches.</p>
                    ) : (
                        filtered.map((c) => {
                            const active = c.code === value;
                            return (
                                <button
                                    key={c.code}
                                    type="button"
                                    onMouseDown={(e) => { e.preventDefault(); pick(c); }}
                                    className={`w-full flex items-center gap-2.5 text-left px-3 py-2 text-[13.5px] transition-colors ${
                                        active ? 'bg-foreground/[0.04] font-medium' : 'hover:bg-foreground/[0.04]'
                                    }`}
                                >
                                    <span className="text-[16px] leading-none">{c.flag}</span>
                                    <span className="flex-1 truncate">{c.name}</span>
                                    <span className="text-[11px] text-muted-foreground tracking-wide">{c.code}</span>
                                </button>
                            );
                        })
                    )}
                </div>
            )}
        </div>
    );
}
