import type { AllergyView } from "@batch-cooking/shared";
import { useTranslation } from "react-i18next";
import { CheckboxOption } from "../../components/ui/Checkbox";
import "./profile-forms.scss";

interface AllergySelectProps {
  legend: string;
  allergies: AllergyView[];
  value: number[];
  onChange: (allergyIds: number[]) => void;
}

/**
 * Multi-select (checkbox grid, not a native `<select multiple>` — far more
 * discoverable/tappable, especially on the mobile viewport this app is
 * eventually embedded into via Capacitor) for a group of allergens. Used
 * both by the signup wizard's allergens step and the `/parametres/preferences`
 * settings page, and rendered *twice* by each — once for allergies, once for
 * intolerances (`AllergyView.kind` groups them; callers filter and pass
 * two separate lists rather than this component knowing about the split).
 * An empty `value` is a normal, valid state (no declared allergies, or
 * this skippable step was skipped), not an incomplete one.
 *
 * `legend` (not a fixed internal label) — the same component serves both
 * groups, only the heading differs. A `<fieldset>`/`<legend>` (not a bare
 * `<label>`, which only associates with a single control) is the correct
 * semantic label for a group of checkboxes.
 *
 * Receives `allergies` as a prop rather than fetching them itself — same
 * rationale as `DietSelect`.
 */
export function AllergySelect({ legend, allergies, value, onChange }: AllergySelectProps) {
  const { t } = useTranslation();

  function toggle(id: number) {
    onChange(value.includes(id) ? value.filter((existing) => existing !== id) : [...value, id]);
  }

  return (
    <fieldset className="allergy-select">
      <legend>{legend}</legend>
      {allergies.map((allergy) => {
        const checked = value.includes(allergy.id);
        return (
          <CheckboxOption
            key={allergy.id}
            checked={checked}
            onChange={() => toggle(allergy.id)}
            className="allergy-select__option"
          >
            {t(`catalog.allergens.${allergy.key}`)}
          </CheckboxOption>
        );
      })}
    </fieldset>
  );
}
