"use client";

import { useMemo } from "react";
import Field from "./Field";
import { SearchDropdown } from "../SearchDropdown";

export interface CountryOption {
  code: string;
  name: string;
}

export interface CountryComboboxProps {
  id: string;
  label: string;
  options: CountryOption[];
  value: string;
  onChange: (code: string) => void;
  onBlur?: () => void;
  required?: boolean;
  error?: string;
  hint?: string;
  placeholder?: string;
  /** Forwarded to the underlying Field's root `.lf-field` div. */
  className?: string;
}

/**
 * Country picker.
 *
 * A native `<select>` is the wrong control at this length: 249 options with no
 * way to type-filter means scrolling, and the same list appears up to four
 * times per passenger (nationality, issuing country, residence). The combobox
 * underneath already exists and is used by the profile page — this only wires
 * it to `Field` so label, hint and error are announced with it.
 */
export default function CountryCombobox({
  id,
  label,
  options,
  value,
  onChange,
  onBlur,
  required,
  error,
  hint,
  placeholder = "Select country",
  className,
}: CountryComboboxProps) {
  const items = useMemo(
    () => options.map((c) => ({ value: c.code, label: c.name })),
    [options]
  );

  return (
    <Field id={id} label={label} required={required} hint={hint} error={error} className={className}>
      {(a11y) => (
        <div
          className={[
            "lf-combobox",
            error ? "lf-combobox--invalid" : "",
            value ? "" : "lf-combobox--placeholder",
          ]
            .filter(Boolean)
            .join(" ")}
        >
          <SearchDropdown
            id={a11y.id}
            variant="bare"
            suppressError
            options={items}
            value={value}
            onChange={onChange}
            onBlur={onBlur}
            placeholder={placeholder}
            searchPlaceholder="Search country"
            ariaDescribedBy={a11y["aria-describedby"]}
            ariaRequired={required}
            error={error}
          />
        </div>
      )}
    </Field>
  );
}
