"use client";

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

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

/**
 * Step 1 of the reset flow: ask for the address.
 *
 * The confirmation copy is deliberately non-committal ("if an account exists"),
 * matching an endpoint that answers the same way for registered and unknown
 * addresses alike.
 */
export function ForgotPasswordForm() {
  const { language } = useI18n();
  const isDe = language === "de";

  const formRef = useRef<HTMLFormElement>(null);
  const [email, setEmail] = useState("");
  const [fieldError, setFieldError] = useState<string | null>(null);
  const [formError, setFormError] = useState<string | null>(null);
  const [status, setStatus] = useState<Status>("idle");
  const [devLink, setDevLink] = useState<string | null>(null);

  // Localised messages would otherwise be stranded in the previous language.
  useEffect(() => {
    setFieldError(null);
    setFormError(null);
  }, [isDe]);

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

    const invalid = validateEmail(email, isDe);
    setFieldError(invalid);
    setFormError(null);
    if (invalid) {
      requestAnimationFrame(() => {
        formRef.current?.querySelector<HTMLInputElement>('[aria-invalid="true"]')?.focus();
      });
      return;
    }

    setStatus("submitting");
    try {
      const response = await apiFetch("/api/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, lang: isDe ? "de" : "en" }),
      });

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

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

      if (typeof data.devLink === "string") setDevLink(data.devLink);
      setStatus("sent");
    } catch {
      setStatus("idle");
      setFormError(authErrorMessage("server_error", isDe));
    }
  };

  if (status === "sent") {
    return (
      <div>
        <div className="w-12 h-12 border border-black flex items-center justify-center mb-5">
          <MailCheck className="w-6 h-6 text-black" 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 ? "E-Mail unterwegs" : "Email on its way"}
          </span>
        </div>

        <h1 className="font-display text-[28px] sm:text-[32px] font-bold tracking-tighter text-black leading-[1.1]">
          {isDe ? "Prüfe dein Postfach" : "Check your inbox"}
        </h1>

        <p className="text-[14px] text-[#64748B] mt-2.5 leading-relaxed">
          {isDe ? "Falls ein Konto zu " : "If an account exists for "}
          <span className="text-black font-medium break-all">{email}</span>
          {isDe
            ? " existiert, ist ein Link zum Zurücksetzen unterwegs."
            : ", a reset link is on its way."}
        </p>

        <div className="mt-5 border border-[#E2E8F0] bg-[#F8FAFC] p-4 space-y-2 font-mono text-[11px] uppercase tracking-wider text-[#64748B]">
          <p>{isDe ? "· Link ist 1 Stunde gültig" : "· Link is valid for 1 hour"}</p>
          <p>{isDe ? "· Nur einmal verwendbar" : "· Single use only"}</p>
          <p>
            {isDe
              ? "· Danach wirst du überall abgemeldet"
              : "· Resetting signs you out everywhere"}
          </p>
        </div>

        {devLink && (
          <div className="mt-4 border border-dashed border-[#C4C7C9] bg-white p-3.5">
            <p className="font-mono text-[10px] uppercase tracking-wider text-[#B45309] mb-1.5">
              {isDe ? "Dev-Modus · kein SMTP konfiguriert" : "Dev mode · SMTP not configured"}
            </p>
            <a
              href={devLink}
              className="text-[12px] text-[#475569] underline break-all hover:text-black"
            >
              {devLink}
            </a>
          </div>
        )}

        <div className="mt-6 flex flex-col sm:flex-row gap-2.5">
          <button
            type="button"
            onClick={() => {
              setStatus("idle");
              setDevLink(null);
            }}
            className="flex-1 h-11 flex items-center justify-center border border-black bg-white text-black font-mono text-[11px] uppercase tracking-caps font-medium hover:bg-black hover:text-white transition-colors"
          >
            {isDe ? "Andere Adresse" : "Different address"}
          </button>
          <Link
            href="/auth/login"
            className="flex-1 h-11 flex items-center justify-center border border-[#E2E8F0] bg-white text-[#475569] font-mono text-[11px] uppercase tracking-caps hover:border-black hover:text-black transition-colors"
          >
            {isDe ? "Zur Anmeldung" : "To sign in"}
          </Link>
        </div>
      </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 ? "Passwort-Reset" : "Password reset"}
        </span>
      </div>

      <h1 className="font-display text-[30px] sm:text-[36px] font-bold tracking-tighter text-black leading-[1.1]">
        {isDe ? "Passwort vergessen?" : "Forgot your password?"}
      </h1>
      <p className="text-[14px] text-[#64748B] mt-2 leading-relaxed">
        {isDe
          ? "Gib deine E-Mail-Adresse ein. Wir senden dir einen Link, mit dem du ein neues Passwort festlegst."
          : "Enter your email address and we'll send you a link to choose a new password."}
      </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" />
          <span>{formError}</span>
        </div>
      )}

      <form ref={formRef} onSubmit={submit} noValidate className="mt-6 space-y-4">
        <AuthField
          label={isDe ? "E-Mail-Adresse" : "Email address"}
          icon={Mail}
          type="email"
          name="email"
          autoComplete="email"
          inputMode="email"
          autoCapitalize="none"
          spellCheck={false}
          placeholder="name@unternehmen.de"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          error={fieldError}
          disabled={status === "submitting"}
          autoFocus
        />

        <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 ? "Einen Moment…" : "One moment…"}</span>
            </>
          ) : (
            <>
              <span>{isDe ? "Reset-Link senden" : "Send reset link"}</span>
              <ArrowRight className="w-3.5 h-3.5" aria-hidden="true" />
            </>
          )}
        </button>
      </form>

      <div className="mt-6 pt-5 border-t border-[#E2E8F0] flex items-center justify-between gap-3 text-[13px] text-[#64748B]">
        <span>{isDe ? "Passwort wieder eingefallen?" : "Remembered it after all?"}</span>
        <Link
          href="/auth/login"
          className="font-mono text-[11px] uppercase tracking-caps text-black font-medium hover:underline underline-offset-4"
        >
          {isDe ? "Anmelden →" : "Sign in →"}
        </Link>
      </div>

      <p className="mt-5 flex items-start gap-2 text-[12px] text-[#94A3B8] leading-snug">
        <Check className="w-3.5 h-3.5 shrink-0 mt-0.5" aria-hidden="true" />
        {isDe
          ? "Auch bei Google-Konten nutzbar — damit legst du zusätzlich ein Passwort fest."
          : "Works for Google accounts too — it adds a password alongside Google sign-in."}
      </p>
    </div>
  );
}
