"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { AlertTriangle, ArrowRight, CheckCircle2, Loader2, Lock } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { validatePassword } from "@/lib/auth/validation";
import { authErrorMessage } from "@/lib/auth/errors";
import { AuthField } from "./AuthField";
import { PasswordStrengthMeter } from "./PasswordStrengthMeter";
import { apiFetch } from "@/lib/csrf/client";

type Status = "idle" | "submitting" | "done";

/**
 * Step 2 of the reset flow. The token arrives from the server component, which
 * already confirmed it is live — this form only has to handle the case where it
 * expires between page load and submit.
 */
export function ResetPasswordForm({ token }: { token: string }) {
  const { language } = useI18n();
  const isDe = language === "de";

  const formRef = useRef<HTMLFormElement>(null);
  const [password, setPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const [confirmationError, setConfirmationError] = useState<string | null>(null);
  const [formError, setFormError] = useState<string | null>(null);
  const [status, setStatus] = useState<Status>("idle");

  useEffect(() => {
    setPasswordError(null);
    setConfirmationError(null);
    setFormError(null);
  }, [isDe]);

  const submit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (status === "submitting") return;

    const weak = validatePassword(password, isDe, { requireStrength: true });
    const mismatch =
      password !== confirmation
        ? isDe
          ? "Die Passwörter stimmen nicht überein."
          : "The passwords don't match."
        : null;

    setPasswordError(weak);
    setConfirmationError(mismatch);
    setFormError(null);

    if (weak || mismatch) {
      requestAnimationFrame(() => {
        formRef.current?.querySelector<HTMLInputElement>('[aria-invalid="true"]')?.focus();
      });
      return;
    }

    setStatus("submitting");
    try {
      const response = await apiFetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });

      const data = (await response.json().catch(() => ({}))) as Record<string, unknown>;

      if (!response.ok) {
        setStatus("idle");
        const code = data.error as string | undefined;
        if (code === "weak_password") {
          setPasswordError(authErrorMessage(code, isDe));
          return;
        }
        setFormError(
          authErrorMessage(code, isDe, data.retryAfter as number | undefined)
        );
        return;
      }

      setStatus("done");
    } catch {
      setStatus("idle");
      setFormError(authErrorMessage("server_error", isDe));
    }
  };

  if (status === "done") {
    return (
      <div>
        <div className="w-12 h-12 border border-emerald-600 flex items-center justify-center mb-5">
          <CheckCircle2 className="w-6 h-6 text-emerald-600" aria-hidden="true" />
        </div>

        <div className="flex items-center gap-2 mb-3">
          <span className="w-2 h-2 bg-black" aria-hidden="true" />
          <span className="font-mono text-[11px] uppercase tracking-caps text-[#475569] font-bold">
            {isDe ? "Erledigt" : "Done"}
          </span>
        </div>

        <h1 className="font-display text-[28px] sm:text-[32px] font-bold tracking-tighter text-black leading-[1.1]">
          {isDe ? "Passwort geändert" : "Password changed"}
        </h1>
        <p className="text-[14px] text-[#64748B] mt-2.5 leading-relaxed">
          {isDe
            ? "Aus Sicherheitsgründen wurden alle Sitzungen beendet. Melde dich mit dem neuen Passwort an."
            : "For safety, every session was signed out. Sign in with your new password."}
        </p>

        <Link
          href="/auth/login?reset=success"
          className="mt-7 w-full h-12 flex items-center justify-center gap-2 bg-black text-white font-mono text-[12px] uppercase tracking-caps font-medium hover:bg-[#334155] transition-colors"
        >
          <span>{isDe ? "Jetzt anmelden" : "Sign in now"}</span>
          <ArrowRight className="w-3.5 h-3.5" aria-hidden="true" />
        </Link>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center gap-2 mb-3">
        <span className="w-2 h-2 bg-black" aria-hidden="true" />
        <span className="font-mono text-[11px] uppercase tracking-caps text-[#475569] font-bold">
          {isDe ? "Neues Passwort" : "New password"}
        </span>
      </div>

      <h1 className="font-display text-[30px] sm:text-[36px] font-bold tracking-tighter text-black leading-[1.1]">
        {isDe ? "Passwort festlegen" : "Set a new password"}
      </h1>
      <p className="text-[14px] text-[#64748B] mt-2 leading-relaxed">
        {isDe
          ? "Wähle ein neues Passwort. Danach wirst du auf allen Geräten abgemeldet."
          : "Choose a new password. You'll be signed out on every device afterwards."}
      </p>

      {formError && (
        <div
          role="alert"
          className="flex items-start gap-2.5 border border-[#BA1A1A] bg-[#FFDAD6] px-3.5 py-3 mt-6 text-[13px] text-[#93000A] leading-snug"
        >
          <AlertTriangle className="w-4 h-4 shrink-0 mt-px" aria-hidden="true" />
          <div>
            <p>{formError}</p>
            <Link
              href="/auth/forgot-password"
              className="inline-block mt-1.5 font-mono text-[11px] uppercase tracking-caps underline underline-offset-2"
            >
              {isDe ? "Neuen Link anfordern →" : "Request a new link →"}
            </Link>
          </div>
        </div>
      )}

      <form ref={formRef} onSubmit={submit} noValidate className="mt-6 space-y-4">
        <div>
          <AuthField
            label={isDe ? "Neues Passwort" : "New password"}
            icon={Lock}
            type="password"
            name="password"
            autoComplete="new-password"
            placeholder={isDe ? "Mindestens 8 Zeichen" : "At least 8 characters"}
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            error={passwordError}
            disabled={status === "submitting"}
            capsLockHint={isDe ? "Feststelltaste ist aktiv" : "Caps lock is on"}
            autoFocus
          />
          {password.length > 0 && <PasswordStrengthMeter value={password} isDe={isDe} />}
        </div>

        <AuthField
          label={isDe ? "Passwort wiederholen" : "Repeat password"}
          icon={Lock}
          type="password"
          name="password_confirmation"
          autoComplete="new-password"
          placeholder="••••••••••••"
          value={confirmation}
          onChange={(event) => setConfirmation(event.target.value)}
          error={confirmationError}
          disabled={status === "submitting"}
          capsLockHint={isDe ? "Feststelltaste ist aktiv" : "Caps lock is on"}
        />

        <button
          type="submit"
          disabled={status === "submitting"}
          className="w-full h-12 flex items-center justify-center gap-2 bg-black text-white font-mono text-[12px] uppercase tracking-caps font-medium hover:bg-[#334155] transition-colors disabled:pointer-events-none disabled:bg-[#475569]"
        >
          {status === "submitting" ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
              <span>{isDe ? "Wird gespeichert…" : "Saving…"}</span>
            </>
          ) : (
            <>
              <span>{isDe ? "Passwort speichern" : "Save password"}</span>
              <ArrowRight className="w-3.5 h-3.5" aria-hidden="true" />
            </>
          )}
        </button>
      </form>
    </div>
  );
}
