
"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 AdminLoginPage() {
  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((v) => Math.max(v - 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, adminOnly: true });
        router.push('/admin');
        return;
      }
      const result = await apiPost<LoginResponse>('/api/auth/login', { email, password, adminOnly: 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(`An admin sign-in verification code was ${result.deliveryStatus === 'SENT' ? 'sent' : 'prepared'} for ${result.challengeMaskedEmail ?? 'your account email'}.`);
        return;
      }
      router.push('/admin');
    } catch (err: any) {
      setError(err?.message ?? (challengeMode ? 'Failed to verify admin sign-in code' : 'Admin login failed'));
    } 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 admin sign-in code was ${result.deliveryStatus === 'SENT' ? 'sent' : 'prepared'} for ${result.challengeMaskedEmail ?? 'your account email'}.`);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to resend admin sign-in code');
    } 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-slate-950 p-6">
      <div className="w-full max-w-md rounded-3xl border border-slate-800 bg-slate-900 p-8 shadow-sm">
        <div className="mb-6">
          <div className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">Admin Control Plane</div>
          <h1 className="mt-2 text-2xl font-semibold text-white">Dispatch Spot Admin</h1>
          <p className="mt-1 text-sm text-slate-400">{challengeMode ? 'Enter the email verification code to finish signing in as Super Admin' : 'Separate login surface for platform administration only. Workspace users must sign in through the standard workspace login.'}</p>
        </div>
        <form className="space-y-4" onSubmit={onSubmit}>
          {!challengeMode ? (
            <>
              <div><label className="mb-1 block text-sm font-medium text-slate-200">Admin email</label><input className="w-full rounded-xl border border-slate-700 bg-slate-950 px-3 py-2 text-white" value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="admin@dispatchspot.com" autoComplete="username" /></div>
              <div><label className="mb-1 block text-sm font-medium text-slate-200">Password</label><input type="password" className="w-full rounded-xl border border-slate-700 bg-slate-950 px-3 py-2 text-white" 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-900 bg-red-950 text-red-200' : 'border-blue-900 bg-blue-950 text-blue-200'}`}>
                <div className="font-medium">Admin 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-black/20 px-2 py-1">Attempts remaining: <span className="font-semibold">{challengeAttemptsRemaining}</span></span>
                  <span className="rounded-full border border-current/15 bg-black/20 px-2 py-1">Failed attempts: <span className="font-semibold">{challengeFailedAttemptCount}</span></span>
                  <span className="rounded-full border border-current/15 bg-black/20 px-2 py-1">Resend {resendCooldownSeconds > 0 ? `available in ${resendCooldownSeconds}s` : 'available now'}</span>
                </div>
              </div>
              <div><label className="mb-1 block text-sm font-medium text-slate-200">Verification code</label><input className="w-full rounded-xl border border-slate-700 bg-slate-950 px-3 py-2 text-center text-lg tracking-[0.35em] text-white" 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-900 bg-red-950 px-3 py-2 text-sm text-red-200">{error}</div> : null}
          {success ? <div className="rounded-xl border border-emerald-900 bg-emerald-950 px-3 py-2 text-sm text-emerald-200">{success}</div> : null}
          <button type="submit" disabled={isSubmitting || challengeLocked} className="w-full rounded-xl bg-white px-4 py-2.5 text-sm font-medium text-slate-950 disabled:opacity-60">{isSubmitting ? (challengeMode ? 'Verifying...' : 'Signing in...') : (challengeMode ? 'Verify and continue' : 'Sign in to admin')}</button>
          {challengeMode ? (
            <div className="flex items-center justify-between gap-3 text-sm">
              <button type="button" onClick={resetChallenge} className="text-slate-300 underline">Use different login</button>
              <button type="button" onClick={resendCode} disabled={isResending || resendCooldownSeconds > 0 || challengeLocked} className="text-slate-300 underline disabled:opacity-60">{isResending ? 'Resending...' : resendCooldownSeconds > 0 ? `Resend in ${resendCooldownSeconds}s` : 'Resend code'}</button>
            </div>
          ) : (
            <div className="flex items-center justify-between text-sm text-slate-400">
              <Link href="/reset-password" className="underline">Forgot password?</Link>
              <Link href="/login" className="underline">Workspace login</Link>
            </div>
          )}
        </form>
      </div>
    </main>
  );
}
