import { ErrorCode, signupSchema } from "@batch-cooking/shared";
import { type FormEvent, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { ApiError } from "../api/client";
import { useAuth } from "../features/auth/AuthContext";
// Shared with LoginPage — see the file for why it's colocated in
// features/auth/ rather than duplicated per page.
import "../features/auth/auth-form.scss";
import { fieldErrorsFrom } from "../lib/zod-errors";
import { errorMessageService } from "../services/error-message.service";

/**
 * Signup form (profile creation). Validates client-side first (via the
 * shared `signupSchema`, same rules the API enforces) for instant
 * feedback with no network round trip; only calls the API once the
 * payload is locally valid, and translates any API failure (e.g. email
 * already taken) into a localized label via {@link ErrorMessageService}.
 * All static copy comes from i18next (`locales/fr/translation.json`,
 * `auth.signup` namespace) via {@link useTranslation}, not hardcoded JSX text.
 */
export function SignupPage() {
  const { signup } = useAuth();
  const navigate = useNavigate();
  const { t } = useTranslation();

  // Controlled form fields.
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // Per-field validation messages (client-side, from zod) and a whole-form
  // error message (from the API), kept separate since they're displayed
  // in different places and cleared at different times.
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  /** Validates, then submits the form; on success, starts the regime/household/allergens onboarding wizard rather than going straight to the home. */
  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setFormError(null);

    const result = signupSchema.safeParse({ firstName, lastName, email, password });
    if (!result.success) {
      setFieldErrors(fieldErrorsFrom(result.error));
      return;
    }
    setFieldErrors({});

    setIsSubmitting(true);
    try {
      await signup(result.data);
      navigate("/onboarding/regime");
    } catch (err) {
      // ApiError.code is looked up through ErrorMessageService so the
      // label is centralized and localized — never display err.message
      // directly, it's the API's developer-facing (English) text.
      const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setFormError(errorMessageService.getLabel(code));
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <main className="auth-page">
      <form className="auth-card" onSubmit={handleSubmit} noValidate>
        <h1>{t("auth.signup.title")}</h1>

        <label htmlFor="firstName">{t("auth.signup.firstNameLabel")}</label>
        <input
          id="firstName"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
          autoComplete="given-name"
        />
        {fieldErrors.firstName && <p className="field-error">{fieldErrors.firstName}</p>}

        <label htmlFor="lastName">{t("auth.signup.lastNameLabel")}</label>
        <input
          id="lastName"
          value={lastName}
          onChange={(e) => setLastName(e.target.value)}
          autoComplete="family-name"
        />
        {fieldErrors.lastName && <p className="field-error">{fieldErrors.lastName}</p>}

        <label htmlFor="email">{t("auth.signup.emailLabel")}</label>
        <input
          id="email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          autoComplete="email"
        />
        {fieldErrors.email && <p className="field-error">{fieldErrors.email}</p>}

        <label htmlFor="password">{t("auth.signup.passwordLabel")}</label>
        <input
          id="password"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          autoComplete="new-password"
        />
        {fieldErrors.password && <p className="field-error">{fieldErrors.password}</p>}

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

        <button type="submit" disabled={isSubmitting}>
          {isSubmitting ? t("auth.signup.submitting") : t("auth.signup.submit")}
        </button>

        <p className="auth-switch">
          {t("auth.signup.hasAccount")} <Link to="/login">{t("auth.signup.loginLink")}</Link>
        </p>
      </form>
    </main>
  );
}
