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

interface SourceSelectProps {
  legend: string;
  sources: SourceView[];
  value: number[];
  onChange: (sourceIds: number[]) => void;
}

/**
 * Multi-select (checkbox grid) for which recipe sources a household sees
 * in its recipe tabs — same "grid of `CheckboxOption`s" shape as
 * `AllergySelect` (`features/profile/`), but household-scoped rather than
 * per-user, hence its own `features/house/` home. Used both by the
 * onboarding wizard's source step and the `/parametres/foyer` settings
 * page. An empty `value` is this household's normal starting state
 * (opt-in — see `HouseSource` in schema.prisma), not an incomplete one.
 *
 * Unlike `AllergySelect`, a source's display text is its own `name`
 * (`SourceView.name` — a proper noun like "Marmiton"), not resolved
 * through `catalog.<domain>.<key>` i18n — nothing to translate. The
 * `official`/`unofficial` badge next to it is what *is* translated, so a
 * household can tell an official API apart from a scraped site before
 * deciding whether to trust it.
 */
export function SourceSelect({ legend, sources, value, onChange }: SourceSelectProps) {
  const { t } = useTranslation();

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

  return (
    <fieldset className="source-select">
      <legend>{legend}</legend>
      {sources.map((source) => {
        const checked = value.includes(source.id);
        return (
          <CheckboxOption
            key={source.id}
            checked={checked}
            onChange={() => toggle(source.id)}
            className="source-select__option"
          >
            {source.name}
            <span className={`source-select__badge ${source.official ? "is-official" : ""}`}>
              {t(source.official ? "household.sources.official" : "household.sources.unofficial")}
            </span>
          </CheckboxOption>
        );
      })}
    </fieldset>
  );
}
