"use client";

import { Suspense, useState, useEffect, type FormEvent } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Eye, EyeOff, LogIn } from "lucide-react";
import { Button } from "@/components/common/Button";
import { FormField } from "@/components/app/FormField";
import { AGENT_HOME } from "@/constants/routes";
import { isApiError } from "@/lib/apiError";
import { safeRedirect } from "@/lib/safeRedirect";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { useAgentBasicData } from "@/hooks/queries/useAgentDashboard";
import { notify } from "@/lib/notify";
import { useTranslation } from "@/hooks/useTranslation";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export default function AgentLoginPage() {
  return (
    <Suspense fallback={<div className="h-64" />}>
      <AgentLoginForm />
    </Suspense>
  );
}

function AgentLoginForm() {
  const { signIn, user, hydrated } = useAgentAuth();
  const { t } = useTranslation();
  const router = useRouter();
  const { data: basicData } = useAgentBasicData();
  const registrationClosed = basicData?.agent_registration === 0;
  const redirectTo = safeRedirect(useSearchParams().get("redirect"), AGENT_HOME, "agent");

  useEffect(() => {
    if (hydrated && user) {
      router.replace(redirectTo);
    }
  }, [hydrated, user, router, redirectTo]);

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});
  const [formError, setFormError] = useState("");
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    const next: typeof errors = {};
    if (!email) next.email = t("agent.login.emailRequired");
    else if (!EMAIL_RE.test(email)) next.email = t("agent.login.emailInvalid");
    if (!password) next.password = t("agent.login.passwordRequired");
    setErrors(next);
    if (Object.keys(next).length > 0) return;

    setLoading(true);
    setFormError("");
    try {
      const { destination, banned } = await signIn({ email, password });
      if (banned) {
        setFormError(t("agent.login.banned"));
        setLoading(false);
        return;
      }
      // A pending challenge (2FA / email / KYC) always wins; only the plain
      // "signed in" landing is swapped for the page the agent was sent away from.
      router.replace(destination === AGENT_HOME ? redirectTo : destination);
    } catch (err) {
      if (isApiError(err) && err.kind === "validation" && err.fieldErrors) {
        setErrors({ email: err.fieldError("email"), password: err.fieldError("password") });
      } else {
        setFormError(isApiError(err) ? err.message : t("agent.login.invalidCreds"));
      }
      setLoading(false);
    }
  }

  return (
    <div>
      {/* Icon + heading — consistent with the other agent auth pages */}
      <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">
        <LogIn 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.login.title")}
      </h1>
      <p className="mt-2 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.login.subtitle")}
      </p>

      {formError && (
        <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"
        >
          {formError}
        </p>
      )}

      <form noValidate onSubmit={onSubmit} className="mt-8 space-y-4">
        <FormField
          label={t("agent.login.emailLabel")}
          type="email"
          autoComplete="email"
          placeholder="you@example.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          error={errors.email}
          required
        />
        <FormField
          label={t("agent.login.passwordLabel")}
          type={showPw ? "text" : "password"}
          autoComplete="current-password"
          placeholder="Enter your password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          error={errors.password}
          required
          trailing={
            <button
              type="button"
              onClick={() => setShowPw((v) => !v)}
              aria-label={showPw ? t("agent.login.hidePassword") : t("agent.login.showPassword")}
              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>
          }
        />

        <div className="flex justify-end">
          <Link
            href="/agent/forgot-password"
            className="text-xs font-semibold text-brand-600 hover:text-brand-700 dark:text-brand-300"
          >
            {t("agent.login.forgotPassword")}
          </Link>
        </div>

        <Button type="submit" size="md" loading={loading} className="w-full font-bold">
          {loading ? t("agent.login.submitting") : t("agent.login.submit")}
        </Button>
      </form>

      <p className="mt-8 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.login.newAgent")}{" "}
        <Link
          href="/agent/register"
          onClick={(e) => {
            if (registrationClosed) {
              e.preventDefault();
              notify(t("agent.login.registrationClosed"), "warning");
            }
          }}
          className="font-semibold text-brand-600 hover:text-brand-700 dark:text-brand-300"
        >
          {t("agent.login.createAccount")}
        </Link>
      </p>
      <p className="mt-2 text-center text-sm text-slate-600 dark:text-slate-300">
        {t("agent.login.notAgent")}{" "}
        <Link
          href="/login"
          className="font-semibold text-brand-600 hover:text-brand-700 dark:text-brand-300"
        >
          {t("agent.login.userLogin")}
        </Link>
      </p>
    </div>
  );
}
