"use client";

import Link from "next/link";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";

export default function SignInPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [totp, setTotp] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [mfaRequired, setMfaRequired] = useState(false);
  const totpInputRef = useRef<HTMLInputElement>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError("");

    const result = await signIn("credentials", {
      email,
      password,
      ...(mfaRequired ? { totp } : {}),
      redirect: false,
    });

    if (result?.error) {
      // Auth.js v5: CredentialsSignin subclasses forward their `code` via
      // SignInResponse.code (and sometimes also as result.error).
      // Check both fields for compatibility across beta versions.
      const code = result.code ?? result.error;

      if (code === "MFA_REQUIRED_SETUP") {
        // User's role requires MFA but it hasn't been set up yet — redirect to setup
        setLoading(false);
        router.push("/account/security?mfa_required=1");
        return;
      }
      if (code === "MFA_REQUIRED") {
        setMfaRequired(true);
        setLoading(false);
        // Focus the TOTP input after render
        setTimeout(() => totpInputRef.current?.focus(), 100);
        return;
      }
      if (code === "INVALID_TOTP") {
        setError("Invalid verification code. Please try again.");
        setTotp("");
        setLoading(false);
        return;
      }
      setError("Invalid email or password");
      // Reset MFA state on credential error
      if (mfaRequired) {
        setMfaRequired(false);
        setTotp("");
      }
    } else {
      router.push("/dashboard");
    }

    setLoading(false);
  }

  function handleBackToLogin() {
    setMfaRequired(false);
    setTotp("");
    setError("");
  }

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,rgba(255,255,255,0.9),transparent_26rem),linear-gradient(135deg,rgba(240,249,255,1),rgba(232,245,255,0.85)_40%,rgba(255,255,255,1))] px-4 py-12 dark:bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.14),transparent_24rem),linear-gradient(180deg,rgba(12,17,29,1),rgba(10,15,25,1))]">
      <div className="mx-auto grid w-full max-w-6xl gap-8 lg:grid-cols-[1.05fr,0.95fr]">
        <div className="hidden rounded-[2rem] border border-white/70 bg-white/75 p-10 shadow-2xl backdrop-blur lg:flex lg:flex-col lg:justify-between dark:border-slate-800 dark:bg-slate-950/60">
          <div>
            <span className="inline-flex rounded-full border border-brand-200 bg-brand-50 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-brand-700 dark:border-brand-900/50 dark:bg-brand-900/20 dark:text-brand-300">
              CapaKraken Control Center
            </span>
            <h1 className="mt-6 font-display text-5xl font-semibold leading-tight text-gray-900 dark:text-gray-50">
              Resource planning that stays readable under pressure.
            </h1>
            <p className="mt-5 max-w-xl text-lg text-gray-600 dark:text-gray-300">
              Estimates, staffing, chargeability, and timelines in one workspace with sharper structure for day-to-day planning.
            </p>
          </div>
          <div className="grid gap-4 sm:grid-cols-3">
            <div className="app-surface p-5">
              <p className="app-label">Visibility</p>
              <p className="text-sm text-gray-700 dark:text-gray-300">Clearer data density, stronger contrast, faster scanning.</p>
            </div>
            <div className="app-surface p-5">
              <p className="app-label">Planning</p>
              <p className="text-sm text-gray-700 dark:text-gray-300">Dynamic staffing, resources, and chargeability in one flow.</p>
            </div>
            <div className="app-surface p-5">
              <p className="app-label">Control</p>
              <p className="text-sm text-gray-700 dark:text-gray-300">Theme-aware UI that works in bright and dark environments.</p>
            </div>
          </div>
        </div>

        <div className="w-full max-w-md lg:ml-auto lg:max-w-lg">
          <div className="app-surface-strong p-8">
            <div className="mb-8">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">Welcome Back</p>
              <h2 className="mt-3 font-display text-4xl font-semibold text-gray-900 dark:text-gray-50">
                {mfaRequired ? "Two-Factor Authentication" : "Sign in to CapaKraken"}
              </h2>
              <p className="mt-2 text-sm text-gray-500">
                {mfaRequired
                  ? "Enter the 6-digit code from your authenticator app."
                  : "Resource Planning, staffing, and forecasting."}
              </p>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              {error && (
                <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/40 dark:text-red-300">
                  {error}
                </div>
              )}

              {!mfaRequired && (
                <>
                  <div>
                    <label htmlFor="email" className="app-label">
                      Email
                    </label>
                    <input
                      id="email"
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="app-input"
                      placeholder="you@company.com"
                      required
                    />
                  </div>

                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <label htmlFor="password" className="app-label">
                        Password
                      </label>
                      <Link
                        href="/auth/forgot-password"
                        className="text-xs text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300"
                      >
                        Forgot password?
                      </Link>
                    </div>
                    <input
                      id="password"
                      type="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="app-input"
                      placeholder="--------"
                      required
                      autoComplete="current-password"
                    />
                  </div>
                </>
              )}

              {mfaRequired && (
                <div>
                  <label htmlFor="totp" className="app-label">
                    Verification Code
                  </label>
                  <input
                    ref={totpInputRef}
                    id="totp"
                    type="text"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    maxLength={6}
                    pattern="[0-9]{6}"
                    value={totp}
                    onChange={(e) => setTotp(e.target.value.replace(/\D/g, "").slice(0, 6))}
                    className="app-input text-center text-2xl font-mono tracking-[0.4em]"
                    placeholder="000000"
                    required
                  />
                  <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                    Open your authenticator app (e.g. Google Authenticator, Authy) and enter the current code.
                  </p>
                </div>
              )}

              <button
                type="submit"
                disabled={loading || (mfaRequired && totp.length !== 6)}
                className="w-full rounded-2xl bg-brand-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-brand-600/25 transition-colors hover:bg-brand-700 disabled:opacity-50"
              >
                {loading ? "Signing in..." : mfaRequired ? "Verify" : "Sign in"}
              </button>

              {mfaRequired && (
                <button
                  type="button"
                  onClick={handleBackToLogin}
                  className="w-full text-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                >
                  Back to login
                </button>
              )}
            </form>

          </div>
        </div>
      </div>
    </div>
  );
}
