"use client";

import { Suspense, useEffect, useState, type FormEvent } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { MailCheck } from "lucide-react";
import { Button } from "@/components/common/Button";
import { FormField } from "@/components/app/FormField";
import { agentAuthApi } from "@/api/agentAuth.api";
import { useAgentAppSettings } from "@/hooks/queries/useAgentSettings";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { isApiError } from "@/lib/apiError";
import { useTranslation } from "@/hooks/useTranslation";

export default function AgentVerifyEmailPage() {
  return (
    <Suspense fallback={<div className="h-64" />}>
      <AgentVerifyEmailForm />
    </Suspense>
  );
}

function AgentVerifyEmailForm() {
  const router = useRouter();
  const params = useSearchParams();
  const { user, completeVerification } = useAgentAuth();
  const { kycVerificationRequired } = useAgentAppSettings();
  const { t } = useTranslation();

  // signIn/register withhold the session while email is unverified, so `user` isn't
  // set yet on this path — the email travels via query param instead. Still fall back
  // to `user?.email` for the (rare) case this page is revisited with a live session.
  const email = params.get("email") || user?.email || "";

  const [code, setCode]           = useState("");
  const [resendToken, setResendToken] = useState("");
  const [error, setError]         = useState("");
  const [loading, setLoading]     = useState(false);
  const [resending, setResending] = useState(false);
  const [sent, setSent]           = useState(false);
  const [resendCooldown, setResendCooldown] = useState(0);

  // Send code on mount using the known email
  useEffect(() => {
    if (!email || sent) return;
    setSent(true);
    agentAuthApi
      .sendVerifyCode(email)
      .then((res) => {
        const token = (res as Record<string, unknown>).token;
        if (typeof token === "string") setResendToken(token);
        setResendCooldown(60);
      })
      .catch(() => undefined);
  }, [email, sent]);

  useEffect(() => {
    if (resendCooldown <= 0) return;
    const id = setInterval(() => setResendCooldown((s) => Math.max(0, s - 1)), 1000);
    return () => clearInterval(id);
  }, [resendCooldown]);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (!code.trim()) { setError(t("agent.verifyEmail.codeRequired")); return; }
    setLoading(true);
    setError("");
    try {
      await agentAuthApi.verifyEmail(code);
      // signIn/register withhold the session while email is unverified — this
      // promotes it now that the code is confirmed, then routes based on kyc.
      const info = await completeVerification(email);
      const kycCleared = !kycVerificationRequired || Boolean(info.kyc_verified);
      router.replace(kycCleared ? "/agent/dashboard" : "/agent/kyc");
    } catch (err) {
      setError(isApiError(err) ? err.message : "Invalid or expired code. Please try again.");
      setLoading(false);
    }
  }

  async function onResend() {
    if (resending || resendCooldown > 0) return;
    setResending(true);
    setError("");
    try {
      if (resendToken) {
        await agentAuthApi.resendVerifyCode(resendToken);
      } else if (email) {
        const res = await agentAuthApi.sendVerifyCode(email) as Record<string, unknown>;
        const token = res.token;
        if (typeof token === "string") setResendToken(token);
      }
      setResendCooldown(60);
    } catch (err) {
      setError(isApiError(err) ? err.message : "Could not resend code.");
    } finally {
      setResending(false);
    }
  }

  return (
    <div>
      <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">
        <MailCheck 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">
        {t("agent.verifyEmail.title")}
      </h1>
      <p className="mt-2 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.verifyEmail.subtitle").replace("{email}", email || t("agent.verifyEmail.yourEmail"))}
      </p>

      {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>
      )}

      <form noValidate onSubmit={onSubmit} className="mt-8 space-y-4">
        <FormField
          label={t("agent.verifyEmail.codeLabel")}
          type="text"
          inputMode="numeric"
          autoComplete="one-time-code"
          placeholder="000000"
          value={code}
          onChange={(e) => setCode(e.target.value)}
          required
        />
        <Button type="submit" size="md" loading={loading} className="w-full font-bold">
          {loading ? t("agent.verifyEmail.submitting") : t("agent.verifyEmail.submit")}
        </Button>
      </form>

      <button
        type="button"
        disabled={resending || resendCooldown > 0}
        onClick={onResend}
        className="mt-6 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.verifyEmail.resending")
          : resendCooldown > 0
          ? t("agent.verifyEmail.resendIn").replace("{n}", String(resendCooldown))
          : t("agent.verifyEmail.resend")}
      </button>
    </div>
  );
}
