'use client';

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

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

export interface AddressOption {
  id: string;
  label?: string;
  contactName: string;
  city: string;
  countryCode: string;
  isDefaultSender?: boolean;
}

/** A saved address book entry as returned by GET /addresses. */
export interface SavedAddress extends AddressOption {
  companyName?: string;
  email?: string;
  phone: string;
  line1: string;
  line2?: string;
  state?: string;
  postalCode: string;
}

export function AddressPicker({
  id,
  addresses,
  value,
  onChange,
  invalid,
  describedBy,
}: {
  id: string;
  addresses: AddressOption[];
  value: string;
  onChange: (address: AddressOption) => void;
  invalid?: boolean;
  describedBy?: string;
}) {
  const listId = useId();
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [highlight, setHighlight] = useState(0);
  const selected = addresses.find((address) => address.id === value);
  const matches = useMemo(() => {
    const needle = query.trim().toLowerCase();
    return addresses
      .filter((address) => {
        const haystack = `${address.label ?? ''} ${address.contactName} ${address.city} ${address.countryCode} ${countryName(address.countryCode)}`.toLowerCase();
        return needle.length === 0 || haystack.includes(needle);
      })
      .slice(0, 8);
  }, [addresses, query]);

  const choose = (address: AddressOption) => {
    onChange(address);
    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);
      }
    } else if (event.key === 'Escape') {
      setOpen(false);
    }
  };

  return (
    <div className="relative">
      <Input
        id={id}
        role="combobox"
        aria-expanded={open}
        aria-controls={listId}
        aria-autocomplete="list"
        aria-invalid={invalid === true ? true : undefined}
        aria-describedby={describedBy}
        autoComplete="off"
        placeholder={addresses.length === 0 ? 'Your address book is empty' : 'Search the address book'}
        leading={<Search />}
        value={open ? query : selected === undefined ? '' : `${selected.label ?? selected.contactName} · ${selected.city}`}
        onFocus={() => {
          setOpen(true);
          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-72 w-full overflow-auto rounded-lg border border-border bg-surface p-1 shadow-md">
          {matches.length === 0 ? (
            <li className="px-3 py-3 text-small text-muted-foreground">{addresses.length === 0 ? 'No saved addresses yet. Switch to New address.' : 'No matching address'}</li>
          ) : null}
          {matches.map((address, index) => (
            <li
              key={address.id}
              role="option"
              aria-selected={address.id === value}
              className={cn('flex cursor-pointer items-center gap-3 rounded-md px-2.5 py-2', index === highlight ? 'bg-surface-muted' : 'hover:bg-surface-muted')}
              onMouseDown={(event) => event.preventDefault()}
              onMouseEnter={() => setHighlight(index)}
              onClick={() => choose(address)}
            >
              <span className="text-[18px] leading-none" aria-hidden="true">
                {flagEmoji(address.countryCode)}
              </span>
              <span className="min-w-0 flex-1">
                <span className="flex items-center gap-2">
                  <span className="truncate text-small font-semibold text-foreground">{address.label ?? address.contactName}</span>
                  {address.isDefaultSender === true ? <span className="shrink-0 rounded-pill bg-primary-soft px-1.5 text-[10px] font-semibold leading-4 text-primary">Default</span> : null}
                </span>
                <span className="block truncate text-caption text-muted-foreground">
                  {address.label === undefined ? '' : `${address.contactName} · `}
                  {address.city}, {countryName(address.countryCode)}
                </span>
              </span>
              {address.id === value ? <Check className="h-4 w-4 shrink-0 text-primary" aria-hidden="true" /> : null}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
