"use client";

import { useEffect, useState, type FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, KeyRound, Mail, ShieldCheck } from "lucide-react";
import { Button } from "@/components/common/Button";
import { FormField } from "@/components/app/FormField";
import { agentAuthApi } from "@/api/agentAuth.api";
import { isApiError } from "@/lib/apiError";
import { useTranslation } from "@/hooks/useTranslation";

type Step = "email" | "verify" | "reset";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export default function AgentForgotPasswordPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [step, setStep]       = useState<Step>("email");
  const [email, setEmail]     = useState("");
  const [code, setCode]       = useState("");
  const [resendToken, setResendToken] = useState("");
  const [password, setPassword]     = useState("");
  const [confirm, setConfirm]       = useState("");
  const [showPw, setShowPw]         = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading]   = useState(false);
  const [resending, setResending] = useState(false);
  const [resendCooldown, setResendCooldown] = useState(0);
  const [error, setError]       = useState("");
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    if (resendCooldown <= 0) return;
    const id = setInterval(() => setResendCooldown((s) => Math.max(0, s - 1)), 1000);
    return () => clearInterval(id);
  }, [resendCooldown]);

  const STEP_META: Record<Step, { icon: React.ElementType; title: string; subtitle: string }> = {
    email: {
      icon: Mail,
      title: t("agent.forgotPassword.emailTitle"),
      subtitle: t("agent.forgotPassword.emailSubtitle"),
    },
    verify: {
      icon: ShieldCheck,
      title: t("agent.forgotPassword.verifyTitle"),
      subtitle: t("agent.forgotPassword.verifySubtitle"),
    },
    reset: {
      icon: KeyRound,
      title: t("agent.forgotPassword.resetTitle"),
      subtitle: t("agent.forgotPassword.resetSubtitle"),
    },
  };

  function clearErrors() { setError(""); setFieldErrors({}); }

  function applyApiError(err: unknown) {
    if (isApiError(err) && err.kind === "validation" && err.fieldErrors) {
      const fe: Record<string, string> = {};
      for (const [k, v] of Object.entries(err.fieldErrors as Record<string, string[]>)) {
        fe[k] = Array.isArray(v) ? v[0] : String(v);
      }
      setFieldErrors(fe);
    } else {
      setError(isApiError(err) ? err.message : "Something went wrong. Please try again.");
    }
  }

  // ─── Step 1: send OTP ──────────────────────────────────────────────────────

  async function onEmailSubmit(e: FormEvent) {
    e.preventDefault();
    clearErrors();
    if (!email)              { setFieldErrors({ email: t("agent.forgotPassword.emailRequired") }); return; }
    if (!EMAIL_RE.test(email)) { setFieldErrors({ email: t("agent.forgotPassword.emailInvalid") }); return; }

    setLoading(true);
    try {
      const res = await agentAuthApi.forgotPassword(email) as Record<string, unknown>;
      const token = (res as { token?: string }).token ?? "";
      setResendToken(String(token));
      setStep("verify");
      setResendCooldown(60);
    } catch (err) {
      applyApiError(err);
    } finally {
      setLoading(false);
    }
  }

  // ─── Step 2: verify OTP ────────────────────────────────────────────────────

  async function onVerifySubmit(e: FormEvent) {
    e.preventDefault();
    clearErrors();
    if (!code.trim()) { setFieldErrors({ code: t("agent.forgotPassword.otpRequired") }); return; }

    setLoading(true);
    try {
      await agentAuthApi.forgotVerifyOtp(email, code);
      setStep("reset");
    } catch (err) {
      applyApiError(err);
    } finally {
      setLoading(false);
    }
  }

  async function onResend() {
    if (!resendToken || resending || resendCooldown > 0) return;
    setResending(true);
    clearErrors();
    try {
      await agentAuthApi.forgotResendCode(resendToken);
      setResendCooldown(60);
    } catch (err) {
      setError(isApiError(err) ? err.message : "Could not resend code.");
    } finally {
      setResending(false);
    }
  }

  // ─── Step 3: reset password ────────────────────────────────────────────────

  async function onResetSubmit(e: FormEvent) {
    e.preventDefault();
    clearErrors();
    const fe: Record<string, string> = {};
    if (!password)                  fe.password = t("agent.forgotPassword.passwordRequired");
    if (confirm !== password)       fe.password_confirmation = t("agent.forgotPassword.passwordMismatch");
    if (Object.keys(fe).length > 0) { setFieldErrors(fe); return; }

    setLoading(true);
    try {
      await agentAuthApi.forgotReset({ email, code, password, password_confirmation: confirm });
      router.replace("/agent/login");
    } catch (err) {
      applyApiError(err);
    } finally {
      setLoading(false);
    }
  }

  // ─── Render ────────────────────────────────────────────────────────────────

  const meta = STEP_META[step];
  const Icon = meta.icon;

  return (
    <div>
      {/* Icon + heading */}
      <div className="mb-5 mx-auto grid h-16 w-16 place-items-center rounded-2xl bg-gradient-to-br from-brand-50 to-indigo-50 dark:from-brand-500/10 dark:to-indigo-500/10">
        <Icon className="h-8 w-8 text-brand-600 dark:text-brand-300" />
      </div>
      <h1 className="text-center text-2xl font-bold text-slate-900 dark:text-white sm:text-3xl">
        {meta.title}
      </h1>
      <p className="mt-2 text-center text-sm text-slate-600 dark:text-slate-300">{meta.subtitle}</p>

      {/* Form-level error */}
      {error && (
        <p role="alert" className="mt-6 rounded-xl bg-rose-50 px-4 py-3 text-sm font-medium text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">
          {error}
        </p>
      )}

      {/* ── Step 1 ── */}
      {step === "email" && (
        <form noValidate onSubmit={onEmailSubmit} className="mt-8 space-y-4">
          <FormField
            label={t("agent.forgotPassword.emailLabel")}
            type="email"
            autoComplete="email"
            placeholder="you@example.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={fieldErrors.email}
            required
          />
          <Button type="submit" size="md" loading={loading} className="w-full font-bold">
            {loading ? t("agent.forgotPassword.sendingCode") : t("agent.forgotPassword.sendCode")}
          </Button>
        </form>
      )}

      {/* ── Step 2 ── */}
      {step === "verify" && (
        <form noValidate onSubmit={onVerifySubmit} className="mt-8 space-y-4">
          <FormField
            label={t("agent.forgotPassword.otpLabel")}
            type="text"
            inputMode="numeric"
            autoComplete="one-time-code"
            placeholder="000000"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            error={fieldErrors.code}
            required
          />
          <Button type="submit" size="md" loading={loading} className="w-full font-bold">
            {loading ? t("agent.forgotPassword.verifying") : t("agent.forgotPassword.verifyCode")}
          </Button>
          <button
            type="button"
            disabled={resending || resendCooldown > 0}
            onClick={onResend}
            className="w-full text-center text-sm font-semibold text-brand-600 hover:text-brand-700 disabled:opacity-50 dark:text-brand-300"
          >
            {resending
              ? t("agent.forgotPassword.resending")
              : resendCooldown > 0
              ? t("agent.forgotPassword.resendIn").replace("{n}", String(resendCooldown))
              : t("agent.forgotPassword.resend")}
          </button>
        </form>
      )}

      {/* ── Step 3 ── */}
      {step === "reset" && (
        <form noValidate onSubmit={onResetSubmit} className="mt-8 space-y-4">
          <FormField
            label={t("agent.forgotPassword.newPasswordLabel")}
            type={showPw ? "text" : "password"}
            autoComplete="new-password"
            placeholder="Create a password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            error={fieldErrors.password}
            required
            trailing={
              <button
                type="button"
                onClick={() => setShowPw((v) => !v)}
                aria-label={showPw ? "Hide" : "Show"}
                className="inline-flex h-8 w-8 items-center justify-center rounded-full text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
              >
                {showPw ? <EyeOff className="icon-md" /> : <Eye className="icon-md" />}
              </button>
            }
          />
          <FormField
            label={t("agent.forgotPassword.confirmPasswordLabel")}
            type={showConfirm ? "text" : "password"}
            autoComplete="new-password"
            placeholder="Re-enter password"
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            error={fieldErrors.password_confirmation}
            required
            trailing={
              <button
                type="button"
                onClick={() => setShowConfirm((v) => !v)}
                aria-label={showConfirm ? "Hide" : "Show"}
                className="inline-flex h-8 w-8 items-center justify-center rounded-full text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
              >
                {showConfirm ? <EyeOff className="icon-md" /> : <Eye className="icon-md" />}
              </button>
            }
          />
          <Button type="submit" size="md" loading={loading} className="w-full font-bold">
            {loading ? t("agent.forgotPassword.resetting") : t("agent.forgotPassword.resetPassword")}
          </Button>
        </form>
      )}

      <p className="mt-8 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.forgotPassword.rememberPassword")}{" "}
        <Link href="/agent/login" className="font-semibold text-brand-600 hover:text-brand-700 dark:text-brand-300">
          {t("agent.forgotPassword.backToSignIn")}
        </Link>
      </p>
    </div>
  );
}
