import { adminLoginSchema, ErrorCode } from "@batch-cooking/shared";
import { type FormEvent, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { AdminApiError } from "../../../api/admin-client";
import { useAdminAuth } from "../../../features/admin/AdminAuthContext";
import "../../../features/admin/admin-auth.scss";
import { fieldErrorsFrom } from "../../../lib/zod-errors";
import { errorMessageService } from "../../../services/error-message.service";

/**
 * The admin login screen — the only unauthenticated route under `/admin`.
 * Client-side validation via the shared `adminLoginSchema` (same rules the
 * API enforces), then `POST /admin/auth/login`; any API failure is
 * translated to a localized label via {@link ErrorMessageService}. Same
 * structure as the user-facing `LoginPage` (`pages/auth/`).
 */
export function AdminLoginPage() {
  const { login } = useAdminAuth();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setFormError(null);

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

    setIsSubmitting(true);
    try {
      await login(result.data);
      void navigate("/admin");
    } catch (err) {
      const code = err instanceof AdminApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setFormError(errorMessageService.getLabel(code));
    } finally {
      setIsSubmitting(false);
    }
  }

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

        <label htmlFor="email">{t("admin.login.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("admin.login.passwordLabel")}</label>
        <input
          id="password"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          autoComplete="current-password"
        />
        {fieldErrors.password && <p className="field-error">{fieldErrors.password}</p>}

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

        <button type="submit" disabled={isSubmitting}>
          {isSubmitting ? t("admin.login.submitting") : t("admin.login.submit")}
        </button>
      </form>
    </main>
  );
}
