import type { DietView } from "@batch-cooking/shared";
import { ErrorCode } from "@batch-cooking/shared";
import { type FormEvent, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { ApiError, apiClient } from "../../api/client";
import { useAuth } from "../../features/auth/AuthContext";
import { DietSelect } from "../../features/profile/DietSelect";
import { errorMessageService } from "../../services/error-message.service";
import "./onboarding.scss";

/**
 * First step of the post-signup onboarding wizard, routed at
 * `/onboarding/regime`. Initial selection comes from `useAuth()`'s
 * already-loaded profile (`user.dietId`) — freshly signed-up, this is
 * `null` — no extra fetch needed just to know the starting value, unlike
 * the household step which has no such shortcut for the current name.
 */
export function OnboardingDietPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user } = useAuth();

  const [diets, setDiets] = useState<DietView[]>([]);
  const [dietId, setDietId] = useState<number | null>(user?.dietId ?? null);
  const [isLoading, setIsLoading] = useState(true);
  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    let cancelled = false;
    apiClient
      .getDiets()
      .then((result) => {
        if (!cancelled) setDiets(result);
      })
      // Not essential for this step to render — the diet list just stays
      // empty (nothing to pick, "Aucun régime particulier" still works)
      // rather than stranding the visitor over a transient failure, same
      // reasoning as OnboardingSourcesPage's own catch.
      .catch(() => {})
      .finally(() => {
        if (!cancelled) setIsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setFormError(null);
    setIsSubmitting(true);
    try {
      await apiClient.updateDiet(dietId);
      void navigate("/onboarding/foyer");
    } catch (err) {
      const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setFormError(errorMessageService.getLabel(code));
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <main className="onboarding-page">
      <form className="onboarding-card" onSubmit={handleSubmit} noValidate>
        <p className="onboarding-step">{t("onboarding.step", { current: 1, total: 3 })}</p>
        <h1>{t("onboarding.diet.title")}</h1>

        {isLoading ? (
          <p>{t("onboarding.loading")}</p>
        ) : (
          <DietSelect diets={diets} value={dietId} onChange={setDietId} />
        )}

        {formError && <p className="form-error">{formError}</p>}

        <button type="submit" disabled={isSubmitting || isLoading}>
          {t("onboarding.continue")}
        </button>
      </form>
    </main>
  );
}
