// @design-system: primitives/CountryCodeSelect

'use client';

import { useState, useRef, useCallback, type KeyboardEvent } from 'react';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/overlays/Popover';
import { Input } from '@/components/ui/primitives/Input';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { COUNTRY_CODES, type CountryCode } from './country-codes';

// ─── Inline icons (no dependency on Icon component to avoid circular deps) ─

function ChevronDownIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

// ─── Props ────────────────────────────────────────────────────────────────

export interface CountryCodeSelectProps {
  /** ISO 3166-1 alpha-2 country code (e.g. "IL", "US") */
  value: string;
  /** Called with ISO code when user selects a country */
  onChange: (isoCode: string) => void;
  disabled?: boolean;
}

// ─── Component ────────────────────────────────────────────────────────────

export function CountryCodeSelect({ value, onChange, disabled }: CountryCodeSelectProps) {
  const t = useT('auth_flow');
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const searchRef = useRef<HTMLInputElement>(null);

  // COUNTRY_CODES[0] is always Israel (+972), safe non-null assertion

  const selected: CountryCode = COUNTRY_CODES.find((c) => c.code === value) ?? COUNTRY_CODES[0]!;

  const filtered = searchQuery.trim()
    ? COUNTRY_CODES.filter((c) => {
        const q = searchQuery.toLowerCase();
        return (
          c.nameEn.toLowerCase().includes(q) ||
          c.nameHe.includes(searchQuery) ||
          c.dialCode.includes(q)
        );
      })
    : COUNTRY_CODES;

  const handleOpenChange = useCallback((nextOpen: boolean) => {
    setOpen(nextOpen);
    if (!nextOpen) {
      // Reset search on close
      setSearchQuery('');
    }
  }, []);

  const handleSelect = useCallback(
    (isoCode: string) => {
      onChange(isoCode);
      setOpen(false);
      setSearchQuery('');
    },
    [onChange],
  );

  const listboxRef = useRef<HTMLDivElement>(null);

  const handleListboxKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
    const buttons = Array.from(
      e.currentTarget.querySelectorAll<HTMLElement>('button[role="option"]'),
    );
    if (!buttons.length) return;
    const idx = buttons.indexOf(document.activeElement as HTMLElement);
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      buttons[(idx + 1) % buttons.length]?.focus();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      buttons[(idx - 1 + buttons.length) % buttons.length]?.focus();
    } else if (e.key === 'Home') {
      e.preventDefault();
      buttons[0]?.focus();
    } else if (e.key === 'End') {
      e.preventDefault();
      buttons[buttons.length - 1]?.focus();
    }
  }, []);

  const handleSearchKeyDown = useCallback((e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      listboxRef.current?.querySelector<HTMLElement>('button[role="option"]')?.focus();
    }
  }, []);

  return (
    <Popover open={open} onOpenChange={handleOpenChange}>
      <PopoverTrigger asChild>
        <button
          type="button"
          disabled={disabled}
          aria-label={t('country_code_label')}
          aria-haspopup="listbox"
          aria-expanded={open}
          className={cn(
            'flex items-center gap-1',
            'border-border-default bg-surface-base rounded-md border',
            'py-2 ps-3 pe-2',
            'text-base text-neutral-900',
            'transition-colors',
            'focus-visible:border-brand-primary-500 focus-visible:ring-brand-primary-500/40 focus-visible:ring-2 focus-visible:outline-none',
            'disabled:cursor-not-allowed disabled:bg-neutral-100 disabled:text-neutral-400',
            'shrink-0 whitespace-nowrap',
          )}
        >
          <span aria-hidden="true">{selected.flag}</span>
          <span className="text-neutral-500">
            <ChevronDownIcon />
          </span>
        </button>
      </PopoverTrigger>

      <PopoverContent
        align="start"
        sideOffset={4}
        className="w-72 p-2"
        onOpenAutoFocus={(e) => {
          e.preventDefault();
          searchRef.current?.focus();
        }}
      >
        <div className="mb-2">
          <Input
            ref={searchRef}
            type="search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onKeyDown={handleSearchKeyDown}
            placeholder={t('search_country')}
            className="text-sm"
          />
        </div>

        <div
          ref={listboxRef}
          role="listbox"
          tabIndex={-1}
          aria-label={t('country_code_label')}
          className="max-h-60 overflow-y-auto"
          onKeyDown={handleListboxKeyDown}
        >
          {filtered.length === 0 ? (
            <p className="py-4 text-center text-sm text-neutral-500">—</p>
          ) : (
            filtered.map((country) => {
              const isSelected = country.code === value;
              return (
                <button
                  key={country.code}
                  type="button"
                  role="option"
                  aria-selected={isSelected}
                  onClick={() => handleSelect(country.code)}
                  className={cn(
                    'flex w-full items-center gap-2',
                    'rounded-sm px-3 py-2',
                    'text-start text-sm text-neutral-900',
                    'cursor-pointer',
                    'transition-colors',
                    'hover:bg-brand-primary-50 hover:text-brand-primary-900',
                    'focus-visible:bg-brand-primary-50 focus-visible:text-brand-primary-900 focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset',
                    isSelected && 'bg-brand-primary-50 text-brand-primary-900',
                  )}
                >
                  <span aria-hidden="true" className="shrink-0">
                    {country.flag}
                  </span>
                  <span className="min-w-0 flex-1 truncate">{country.nameHe}</span>
                  <span className="shrink-0 text-neutral-500">{country.dialCode}</span>
                </button>
              );
            })
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
