"use client";

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

export interface SelectOption {
  value: string;
  label: string;
}

export interface SelectFieldProps {
  id: string;
  label: string;
  options: SelectOption[];
  value: string;
  onChange: (value: string) => void;
  onBlur?: () => void;
  required?: boolean;
  error?: string;
  hint?: string;
  placeholder?: string;
  /** Only shown once the list is long enough to be worth filtering. */
  searchPlaceholder?: string;
}

/**
 * Single-select on an arbitrary option list.
 *
 * `CountryCombobox` is the same idea fixed to the ISO-3166 list; this is for
 * everything else a form needs to choose from — gender, relationship, meal,
 * berth, airline, or a nationality list that is keyed by database id rather
 * than country code. Sharing `Field` is the point: label, hint and error get
 * wired to the control identically whichever of the three a form reaches for.
 */
export default function SelectField({
  id,
  label,
  options,
  value,
  onChange,
  onBlur,
  required,
  error,
  hint,
  placeholder = "Select",
  searchPlaceholder,
}: SelectFieldProps) {
  // Below about a dozen entries a filter box is more friction than help, so
  // the search field only appears once the list is genuinely long.
  const search = useMemo(
    () => searchPlaceholder ?? (options.length > 12 ? `Search ${label.toLowerCase()}` : undefined),
    [searchPlaceholder, options.length, label]
  );

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