"use client";

import { Suspense, useState, type FormEvent } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ShieldCheck } from "lucide-react";
import { Button } from "@/components/common/Button";
import { OtpInput } from "@/components/app/OtpInput";
import { OTP_LENGTH } from "@/constants/auth";
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 AgentVerify2FAPage() {
  return (
    <Suspense fallback={<div className="h-64" />}>
      <AgentVerify2FAForm />
    </Suspense>
  );
}

function AgentVerify2FAForm() {
  const router = useRouter();
  const params = useSearchParams();
  const { completeVerification } = useAgentAuth();
  const { emailVerificationRequired, kycVerificationRequired } = useAgentAppSettings();
  const { t } = useTranslation();
  const [otp, setOtp]         = useState("");
  const [error, setError]     = useState("");
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (otp.length !== OTP_LENGTH) { setError(t("agent.verify2FA.codeRequired")); return; }
    setLoading(true);
    setError("");
    try {
      await agentAuthApi.verifyTwoFactor(otp);
      // signIn withholds the session while 2FA is pending — this promotes it now
      // that the otp is confirmed, then routes based on the remaining challenges.
      const email = params.get("email") ?? "";
      const info = await completeVerification(email);
      if (emailVerificationRequired && !info.email_verified) {
        router.replace(`/agent/verify-email?email=${encodeURIComponent(email)}`);
      } else if (kycVerificationRequired && !info.kyc_verified) {
        router.replace("/agent/kyc");
      } else {
        router.replace("/agent/dashboard");
      }
    } catch (err) {
      setError(isApiError(err) ? err.message : "Invalid code. Please try again.");
      setLoading(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">
        <ShieldCheck 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.verify2FA.title")}
      </h1>
      <p className="mt-2 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.verify2FA.subtitle")}
      </p>

      <form noValidate onSubmit={onSubmit} className="mt-8 space-y-6">
        <div>
          <label className="mb-3 block text-center text-xs font-semibold capitalize tracking-wide text-slate-500 dark:text-slate-400">
            {t("agent.verify2FA.codeLabel")}
          </label>
          <OtpInput
            value={otp}
            onChange={(v) => {
              setOtp(v);
              setError("");
            }}
            ariaLabel={t("agent.verify2FA.codeLabel")}
            autoFocus
            invalid={!!error}
          />
          {error && (
            <p role="alert" className="mt-3 text-center text-xs font-medium text-rose-600 dark:text-rose-400">
              {error}
            </p>
          )}
        </div>

        <Button type="submit" size="md" loading={loading} className="w-full font-bold">
          {loading ? t("agent.verify2FA.submitting") : t("agent.verify2FA.submit")}
        </Button>
      </form>
    </div>
  );
}
