'use client';

import { Check, ChevronDown } from 'lucide-react';
import { useId, useMemo, useState, type KeyboardEvent } from 'react';

import { Input } from '@/components/ui/input';
import { flagEmoji } from '@/lib/format';
import { COUNTRIES } from '@/lib/regions';
import { cn } from '@/lib/utils';

/** Searchable country picker with flag emoji. */
export function CountryCombobox({
  id,
  value,
  onChange,
  labelledBy,
  invalid,
  describedBy,
}: {
  id: string;
  value: string;
  onChange: (code: string) => void;
  labelledBy?: string;
  invalid?: boolean;
  describedBy?: string;
}) {
  const listId = useId();
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [highlight, setHighlight] = useState(0);
  const selected = COUNTRIES.find((country) => country.code === value);
  const matches = useMemo(() => {
    const needle = query.trim().toLowerCase();
    return COUNTRIES.filter((country) => needle.length === 0 || country.name.toLowerCase().includes(needle) || country.code.toLowerCase() === needle).slice(0, 8);
  }, [query]);

  const choose = (code: string) => {
    onChange(code);
    setOpen(false);
  };

  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'ArrowDown') {
      event.preventDefault();
      setOpen(true);
      setHighlight((current) => Math.min(matches.length - 1, current + 1));
    } else if (event.key === 'ArrowUp') {
      event.preventDefault();
      setHighlight((current) => Math.max(0, current - 1));
    } else if (event.key === 'Enter' && open) {
      const match = matches[highlight];
      if (match !== undefined) {
        event.preventDefault();
        choose(match.code);
      }
    } else if (event.key === 'Escape') {
      setOpen(false);
    }
  };

  return (
    <div className="relative">
      <Input
        id={id}
        aria-labelledby={labelledBy}
        role="combobox"
        aria-expanded={open}
        aria-controls={listId}
        aria-autocomplete="list"
        aria-invalid={invalid === true ? true : undefined}
        aria-describedby={describedBy}
        aria-activedescendant={open && matches[highlight] !== undefined ? `${listId}-${matches[highlight]?.code}` : undefined}
        autoComplete="off"
        value={open ? query : selected?.name ?? ''}
        placeholder="Search countries"
        leading={<span className="text-[17px] not-italic leading-none">{selected === undefined ? '🌐' : flagEmoji(selected.code)}</span>}
        trailing={<ChevronDown className="mr-2.5 h-4 w-4 text-subtle-foreground" aria-hidden="true" />}
        onFocus={() => {
          setOpen(true);
          setQuery('');
          setHighlight(0);
        }}
        onChange={(event) => {
          setQuery(event.target.value);
          setHighlight(0);
          setOpen(true);
        }}
        onKeyDown={onKeyDown}
        onBlur={() => window.setTimeout(() => setOpen(false), 150)}
      />
      {open ? (
        <ul id={listId} role="listbox" className="absolute z-30 mt-1.5 max-h-64 w-full overflow-auto rounded-lg border border-border bg-surface p-1 shadow-md">
          {matches.length === 0 ? <li className="px-3 py-2 text-small text-muted-foreground">No matching country</li> : null}
          {matches.map((country, index) => (
            <li
              key={country.code}
              id={`${listId}-${country.code}`}
              role="option"
              aria-selected={country.code === value}
              className={cn(
                'flex h-9 cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-small',
                index === highlight ? 'bg-surface-muted' : 'hover:bg-surface-muted',
              )}
              onMouseDown={(event) => event.preventDefault()}
              onMouseEnter={() => setHighlight(index)}
              onClick={() => choose(country.code)}
            >
              <span aria-hidden="true">{flagEmoji(country.code)}</span>
              <span className="flex-1 truncate">{country.name}</span>
              {country.code === value ? <Check className="h-4 w-4 text-primary" aria-hidden="true" /> : null}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
