"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { apiPost } from "@/lib/api";

type LoginResponse = {
  user?: { id: string };
  challengeRequired?: boolean;
  challengeId?: string;
  challengeMaskedEmail?: string;
  challengeExpiresAt?: string;
  deliveryStatus?: string;
  resendCooldownSeconds?: number;
  attemptsRemaining?: number;
  failedAttemptCount?: number;
  challengeLocked?: boolean;
};

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [code, setCode] = useState("");
  const [challengeId, setChallengeId] = useState<string | null>(null);
  const [challengeMaskedEmail, setChallengeMaskedEmail] = useState<string | null>(null);
  const [challengeExpiresAt, setChallengeExpiresAt] = useState<string | null>(null);
  const [challengeAttemptsRemaining, setChallengeAttemptsRemaining] = useState<number>(5);
  const [challengeFailedAttemptCount, setChallengeFailedAttemptCount] = useState<number>(0);
  const [challengeLocked, setChallengeLocked] = useState(false);
  const [resendCooldownSeconds, setResendCooldownSeconds] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isResending, setIsResending] = useState(false);

  const challengeMode = Boolean(challengeId);
  const challengeExpiryLabel = useMemo(() => {
    if (!challengeExpiresAt) return null;
    return new Date(challengeExpiresAt).toLocaleTimeString();
  }, [challengeExpiresAt]);

  useEffect(() => {
    if (resendCooldownSeconds <= 0) return;
    const timer = window.setTimeout(() => {
      setResendCooldownSeconds((value) => Math.max(value - 1, 0));
    }, 1000);
    return () => window.clearTimeout(timer);
  }, [resendCooldownSeconds]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSuccess(null);
    setIsSubmitting(true);

    try {
      if (challengeMode && challengeId) {
        await apiPost("/api/auth/login-challenge/verify", { challengeId, code, workspaceOnly: true });
        router.push("/dispatch");
        return;
      }

      const result = await apiPost<LoginResponse>("/api/auth/login", { email, password, workspaceOnly: true });
      if (result.challengeRequired && result.challengeId) {
        setChallengeId(result.challengeId);
        setChallengeMaskedEmail(result.challengeMaskedEmail ?? null);
        setChallengeExpiresAt(result.challengeExpiresAt ?? null);
        setChallengeAttemptsRemaining(result.attemptsRemaining ?? 5);
        setChallengeFailedAttemptCount(result.failedAttemptCount ?? 0);
        setChallengeLocked(Boolean(result.challengeLocked));
        setResendCooldownSeconds(result.resendCooldownSeconds ?? 60);
        setCode("");
        setSuccess(`A sign-in verification code was ${result.deliveryStatus === "SENT" ? "sent" : "prepared"} for ${result.challengeMaskedEmail ?? "your account email"}.`);
        return;
      }
      router.push("/dispatch");
    } catch (err: any) {
      const message = err?.message ?? (challengeMode ? "Failed to verify sign-in code" : "Login failed");
      setError(message);
      if (challengeMode) {
        const match = String(message).match(/(\d+) attempt/);
        if (match) setChallengeAttemptsRemaining(Number(match[1]));
        if (String(message).toLowerCase().includes("locked")) {
          setChallengeLocked(true);
          setChallengeAttemptsRemaining(0);
        }
      }
    } finally {
      setIsSubmitting(false);
    }
  }

  async function resendCode() {
    if (!challengeId || resendCooldownSeconds > 0 || challengeLocked) return;
    try {
      setIsResending(true);
      setError(null);
      setSuccess(null);
      const result = await apiPost<LoginResponse>("/api/auth/login-challenge/resend", { challengeId });
      if (result.challengeId) setChallengeId(result.challengeId);
      setChallengeMaskedEmail(result.challengeMaskedEmail ?? challengeMaskedEmail);
      setChallengeExpiresAt(result.challengeExpiresAt ?? challengeExpiresAt);
      setChallengeAttemptsRemaining(result.attemptsRemaining ?? 5);
      setChallengeFailedAttemptCount(result.failedAttemptCount ?? 0);
      setChallengeLocked(Boolean(result.challengeLocked));
      setResendCooldownSeconds(result.resendCooldownSeconds ?? 60);
      setCode("");
      setSuccess(`A fresh sign-in code was ${result.deliveryStatus === "SENT" ? "sent" : "prepared"} for ${result.challengeMaskedEmail ?? "your account email"}.`);
    } catch (err: any) {
      const message = err?.message ?? "Failed to resend sign-in code";
      setError(message);
      const cooldownMatch = String(message).match(/wait (\d+) seconds/i);
      if (cooldownMatch) setResendCooldownSeconds(Number(cooldownMatch[1]));
      if (String(message).toLowerCase().includes("locked")) {
        setChallengeLocked(true);
        setChallengeAttemptsRemaining(0);
      }
    } finally {
      setIsResending(false);
    }
  }

  function resetChallenge() {
    setChallengeId(null);
    setChallengeMaskedEmail(null);
    setChallengeExpiresAt(null);
    setChallengeAttemptsRemaining(5);
    setChallengeFailedAttemptCount(0);
    setChallengeLocked(false);
    setResendCooldownSeconds(0);
    setCode("");
    setError(null);
    setSuccess(null);
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-gray-50 p-6">
      <div className="w-full max-w-md rounded-3xl border bg-white p-8 shadow-sm">
        <div className="mb-6">
          <h1 className="text-2xl font-semibold">Dispatch Spot</h1>
          <p className="mt-1 text-sm text-gray-500">
            {challengeMode ? "Enter the email verification code to finish signing in" : "Sign in to your company workspace"}
          </p>
        </div>

        <form className="space-y-4" onSubmit={onSubmit}>
          {!challengeMode ? (
            <>
              <div>
                <label className="mb-1 block text-sm font-medium">Email</label>
                <input className="w-full rounded-xl border px-3 py-2 outline-none ring-0" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="admin@company.com" autoComplete="username" />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Password</label>
                <input type="password" className="w-full rounded-xl border px-3 py-2 outline-none ring-0" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" autoComplete="current-password" />
              </div>
            </>
          ) : (
            <>
              <div className={`rounded-2xl border px-4 py-3 text-sm ${challengeLocked ? "border-red-200 bg-red-50 text-red-800" : "border-blue-200 bg-blue-50 text-blue-800"}`}>
                <div className="font-medium">Email sign-in challenge</div>
                <div className="mt-1">Enter the 6-digit code sent to {challengeMaskedEmail ?? "your account email"}.</div>
                {challengeExpiryLabel ? <div className="mt-1 text-xs">Code expires around {challengeExpiryLabel}.</div> : null}
                <div className="mt-2 flex flex-wrap gap-2 text-[11px]">
                  <span className="rounded-full border border-current/15 bg-white/70 px-2 py-1">Attempts remaining: <span className="font-semibold">{challengeAttemptsRemaining}</span></span>
                  <span className="rounded-full border border-current/15 bg-white/70 px-2 py-1">Failed attempts: <span className="font-semibold">{challengeFailedAttemptCount}</span></span>
                  <span className="rounded-full border border-current/15 bg-white/70 px-2 py-1">Resend {resendCooldownSeconds > 0 ? `available in ${resendCooldownSeconds}s` : "available now"}</span>
                  {challengeLocked ? <span className="rounded-full border border-current/15 bg-white/70 px-2 py-1 font-semibold">Challenge locked</span> : null}
                </div>
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">Verification code</label>
                <input className="w-full rounded-xl border px-3 py-2 text-center text-lg tracking-[0.35em] outline-none ring-0" value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))} placeholder="123456" inputMode="numeric" autoComplete="one-time-code" disabled={challengeLocked} />
              </div>
            </>
          )}

          {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{error}</div> : null}
          {success ? <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">{success}</div> : null}

          <button type="submit" disabled={isSubmitting || challengeLocked} className="w-full rounded-xl bg-black px-4 py-2.5 text-sm font-medium text-white disabled:opacity-60">
            {isSubmitting ? (challengeMode ? "Verifying..." : "Signing in...") : (challengeMode ? "Verify and continue" : "Sign in")}
          </button>

          {challengeMode ? (
            <div className="flex items-center justify-between gap-3 text-sm">
              <button type="button" onClick={resetChallenge} className="text-gray-600 underline">Use different login</button>
              <button type="button" onClick={resendCode} disabled={isResending || resendCooldownSeconds > 0 || challengeLocked} className="text-gray-600 underline disabled:opacity-60">{isResending ? "Resending..." : resendCooldownSeconds > 0 ? `Resend in ${resendCooldownSeconds}s` : "Resend code"}</button>
            </div>
          ) : (
            <div className="text-right text-sm">
              <Link href="/reset-password" className="text-gray-600 underline">Forgot password?</Link>
            </div>
          )}
        </form>

        <div className="mt-6 flex items-center justify-between gap-3 text-sm text-gray-500"><div>New company? <Link href="/sign-up" className="font-medium text-gray-900 underline">Create workspace</Link></div><Link href="/admin/login" className="font-medium text-gray-900 underline">Super Admin login</Link></div>
      </div>
    </main>
  );
}
