// src/components/two-factor-challenge.tsx — second-factor (TOTP) challenge.
// Reached after a correct password when the account has 2FA enabled (the
// twoFactorClient redirects here). Verifies a 6-digit authenticator code, with
// a fallback to a one-time backup code, then lands in the app.
"use client";

import Link from "next/link";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";

// Mirror the login form's destination so 2FA and password sign-in agree.
const AFTER_LOGIN = "/keywords/reservoir";

export function TwoFactorChallenge() {
  const t = useTranslations("TwoFactor");
  const [mode, setMode] = useState<"totp" | "backup">("totp");
  const [code, setCode] = useState("");
  const [trustDevice, setTrustDevice] = useState(false);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setPending(true);
    setError(null);
    const res =
      mode === "totp"
        ? await authClient.twoFactor.verifyTotp({
            code: code.trim(),
            trustDevice,
          })
        : await authClient.twoFactor.verifyBackupCode({
            code: code.trim(),
            trustDevice,
          });
    if (res.error) {
      setPending(false);
      setError(
        res.error.message ??
          (mode === "totp" ? t("invalidCode") : t("invalidBackupCode")),
      );
      return;
    }
    // Verified → a real session now exists. Hard-navigate so the (app) layout
    // re-reads the fresh session cookie.
    window.location.assign(AFTER_LOGIN);
  }

  return (
    <Card>
      <CardContent className="p-6 md:p-8">
        <form onSubmit={submit}>
          <FieldGroup>
            <div className="flex flex-col items-center gap-2 text-center">
              <h1 className="font-bold text-2xl">{t("challengeTitle")}</h1>
              <p className="text-balance text-muted-foreground">
                {mode === "totp" ? t("challengeSubtitle") : t("backupSubtitle")}
              </p>
            </div>
            <Field>
              <FieldLabel htmlFor="tf-code">
                {mode === "totp" ? t("codeLabel") : t("backupCodeLabel")}
              </FieldLabel>
              <Input
                id="tf-code"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                inputMode={mode === "totp" ? "numeric" : "text"}
                autoComplete="one-time-code"
                placeholder={
                  mode === "totp"
                    ? t("codePlaceholder")
                    : t("backupPlaceholder")
                }
                autoFocus
                required
              />
            </Field>
            <Field orientation="horizontal">
              <Checkbox
                id="tf-trust"
                checked={trustDevice}
                onCheckedChange={(v) => setTrustDevice(v === true)}
              />
              <FieldLabel htmlFor="tf-trust" className="font-normal">
                {t("trustDevice")}
              </FieldLabel>
            </Field>
            {error ? (
              <p className="text-destructive text-sm" role="alert">
                {error}
              </p>
            ) : null}
            <Field>
              <Button type="submit" disabled={pending || !code.trim()}>
                {pending ? "…" : t("verifyButton")}
              </Button>
            </Field>
            <Button
              type="button"
              variant="link"
              className="mx-auto h-auto p-0 text-muted-foreground text-sm"
              onClick={() => {
                setMode((m) => (m === "totp" ? "backup" : "totp"));
                setCode("");
                setError(null);
              }}
            >
              {mode === "totp" ? t("useBackupCode") : t("useAuthenticator")}
            </Button>
          </FieldGroup>
        </form>
        {/* Échappatoire : si le cookie 2FA temporaire est invalide/expiré (p.ex.
            après un changement de domaine), la vérification échoue quel que soit
            le code. Revenir à la connexion relance le flux mot de passe et repose
            un cookie frais — sinon l'utilisateur reste bloqué sans issue. */}
        <div className="mt-6 flex flex-col items-center gap-1 border-border/50 border-t pt-4 text-center text-muted-foreground text-sm">
          <Link
            href="/login"
            className="underline underline-offset-4 hover:text-foreground"
          >
            {t("backToLogin")}
          </Link>
          <span>
            {t("needHelp")}{" "}
            <a
              href="mailto:contact@elevaseo.com"
              className="underline underline-offset-4 hover:text-foreground"
            >
              contact@elevaseo.com
            </a>
          </span>
        </div>
      </CardContent>
    </Card>
  );
}
