import { ErrorCode, THEME_PREFERENCES, type ThemePreference } from "@batch-cooking/shared";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ApiError } from "../../api/client";
import { RadioOption } from "../../components/ui/Radio";
import { useTheme } from "../../features/theme/ThemeContext";
import { errorMessageService } from "../../services/error-message.service";
import "./settings-pages.scss";

/** Status of the theme choice's own autosave — see `PreferencesPage` for the same hot-saving pattern. */
type SaveState = "idle" | "saving" | "saved" | "error";

/**
 * User (personalization) preferences — routed at
 * `/parametres/preferences-utilisateur`. Just the theme choice for now
 * (light/dark/system — see `features/theme/ThemeContext.tsx`), meant to
 * grow. Distinct from `/parametres/preferences` ("Préférences
 * alimentaires" — regime/allergies): that page is about the household's
 * food constraints, this one is about how the app itself looks, unrelated
 * concerns that happened to share a name before this page existed.
 */
export function UserPreferencesPage() {
  const { t } = useTranslation();
  const { theme, setTheme } = useTheme();
  const [saveState, setSaveState] = useState<SaveState>("idle");
  const [saveError, setSaveError] = useState<string | null>(null);

  async function handleChange(newTheme: ThemePreference) {
    setSaveState("saving");
    try {
      await setTheme(newTheme);
      setSaveState("saved");
    } catch (err) {
      const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setSaveError(errorMessageService.getLabel(code));
      setSaveState("error");
    }
  }

  return (
    <div className="settings-page">
      <h1>{t("userPreferences.title")}</h1>

      <div className="settings-page__section">
        <fieldset className="theme-select">
          <legend>{t("userPreferences.themeLabel")}</legend>
          {THEME_PREFERENCES.map((option) => {
            const checked = theme === option;
            return (
              <RadioOption
                key={option}
                name="theme"
                value={option}
                checked={checked}
                onChange={handleChange}
                className="theme-select__option"
              >
                {t(`userPreferences.theme.${option}`)}
              </RadioOption>
            );
          })}
        </fieldset>

        {saveState === "saving" && <p className="settings-page__saving">{t("common.saving")}</p>}
        {saveState === "saved" && <p className="settings-page__saved">{t("common.saved")}</p>}
        {saveState === "error" && <p className="field-error">{saveError}</p>}
      </div>
    </div>
  );
}
