"use client";

import { useState } from "react";
import { useActionState } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { loginAction, verifyTotpLoginAction, completeForcedPasswordChangeAction } from "@/lib/actions/auth";
import { Field, SubmitButton } from "@/components/auth/RegisterForm";
import { AuthCardBody } from "@/components/auth/AuthCard";

export function LoginForm({
  locale,
  next,
  titles,
}: {
  locale: string;
  next?: string;
  titles: { login: string; twoFactor: string; passwordChange: string };
}) {
  const t = useTranslations("auth");
  const [state, formAction, pending] = useActionState(loginAction, {});
  const [totpState, totpFormAction, totpPending] = useActionState(verifyTotpLoginAction, {});
  const [pwState, pwFormAction, pwPending] = useActionState(completeForcedPasswordChangeAction, {});
  const [clientError, setClientError] = useState<string | null>(null);

  // Wie bei der Registrierung: leere Pflichtfelder sollen im roten
  // Fehlertext-Stil der Seite erscheinen statt in der browser-eigenen
  // Validierungs-Sprechblase. Falsche Zugangsdaten selbst werden weiterhin
  // serverseitig geprüft (loginAction) — das lässt sich clientseitig naturgemäß
  // nicht vorab feststellen.
  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    const data = new FormData(e.currentTarget);
    const email = String(data.get("email") || "").trim();
    const password = String(data.get("password") || "");
    if (!email || !password) {
      e.preventDefault();
      setClientError(t("validationLoginRequired"));
    } else {
      setClientError(null);
    }
  }

  if (state.mustChangePassword || totpState.mustChangePassword) {
    return (
      <AuthCardBody title={titles.passwordChange}>
        <form action={pwFormAction} className="flex flex-col gap-4">
          <p className="text-sm text-[var(--rk-ink-muted)]">{t("mustChangePasswordPrompt")}</p>
          <Field label={t("newPasswordLabel")} name="password" type="password" autoComplete="new-password" required minLength={8} />
          <Field
            label={t("confirmPasswordLabel")}
            name="confirmPassword"
            type="password"
            autoComplete="new-password"
            required
            minLength={8}
          />
          {pwState.error && <p className="text-sm text-red-400">{pwState.error}</p>}
          <SubmitButton pending={pwPending} label={t("mustChangePasswordSubmit")} />
        </form>
      </AuthCardBody>
    );
  }

  if (state.twoFactorRequired) {
    return (
      <AuthCardBody title={titles.twoFactor}>
        <form action={totpFormAction} className="flex flex-col gap-4">
          <p className="text-sm text-[var(--rk-ink-muted)]">{t("twoFactorPrompt")}</p>
          <Field label={t("twoFactorCodeLabel")} name="code" type="text" autoComplete="one-time-code" required />
          {totpState.error && <p className="text-sm text-red-400">{totpState.error}</p>}
          <SubmitButton pending={totpPending} label={t("twoFactorSubmit")} />
        </form>
      </AuthCardBody>
    );
  }

  return (
    <AuthCardBody title={titles.login}>
      <form action={formAction} onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
        <input type="hidden" name="locale" value={locale} />
        {next && <input type="hidden" name="next" value={next} />}
        <Field label={t("emailLabel")} name="email" type="email" autoComplete="email" required />
        <Field label={t("passwordLabel")} name="password" type="password" autoComplete="current-password" required />
        {(clientError || state.error) && <p className="text-sm text-red-400">{clientError || state.error}</p>}
        <SubmitButton pending={pending} label={t("loginButton")} />
        <div className="flex justify-between text-xs text-[var(--rk-ink-muted)]">
          <Link href="/forgot-password" className="underline hover:text-[var(--rk-ink)]">
            {t("forgotPassword")}
          </Link>
          <span>
            {t("noAccount")}{" "}
            <Link href="/register" className="underline hover:text-[var(--rk-ink)]">
              {t("registerLink")}
            </Link>
          </span>
        </div>
      </form>
    </AuthCardBody>
  );
}
