// @File: src/pages/admin/AdminLogin.tsx
// @Desc: Admin sign-in page. Handles two flows:
//        1. Plain login — POST /api/v1/auth/local/login returns a session JWT.
//        2. MFA-challenge login — the same endpoint returns an `mfa_token`;
//           the UI then asks for the SMS code and posts it together with
//           the token to /api/v1/auth/mfa/challenge/verify to obtain the
//           real session JWT.
//        The final session JWT is stored in localStorage under `token`
//        (same key as the rest of the app) before redirecting to /admin.
import { FormEvent, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  Eye,
  EyeOff,
  Loader2,
  Lock,
  LogIn,
  Mail,
  ShieldCheck,
  Smartphone,
} from "lucide-react";
import {
  adminLoginLocal,
  isMfaRequired,
  mfaChallengeSend,
  mfaChallengeVerify,
} from "@/lib/adminApi";
import { setSession } from "@/lib/auth";

type Stage = "credentials" | "mfa";

export default function AdminLogin() {
  const navigate = useNavigate();
  const [stage, setStage] = useState<Stage>("credentials");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // MFA challenge state.
  const [mfaToken, setMfaToken] = useState<string | null>(null);
  const [mfaPhone, setMfaPhone] = useState<string | null>(null);
  const [mfaCode, setMfaCode] = useState("");
  const [mfaResendIn, setMfaResendIn] = useState(0);
  const [mfaInfo, setMfaInfo] = useState<string | null>(null);

  useEffect(() => {
    if (mfaResendIn <= 0) return;
    const id = window.setTimeout(() => setMfaResendIn((s) => Math.max(0, s - 1)), 1000);
    return () => window.clearTimeout(id);
  }, [mfaResendIn]);

  function completeLogin(data: {
    token: string;
    user_id: string;
    email: string;
    role: string;
  }) {
    if (data.role !== "admin") {
      setError("This account does not have admin access. Please contact your administrator.");
      setLoading(false);
      return;
    }
    setSession({
      token: data.token,
      user_id: data.user_id,
      email: data.email,
      name: null,
      client_id: 0,
    });
    navigate("/admin", { replace: true });
  }

  async function handleCredentialsSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    if (!email.trim() || !password) {
      setError("Please enter your email and password.");
      return;
    }
    setLoading(true);
    try {
      const resp = await adminLoginLocal(email.trim().toLowerCase(), password);
      if (isMfaRequired(resp)) {
        setMfaToken(resp.mfa_token);
        setMfaPhone(resp.phone_masked);
        setMfaCode("");
        setMfaInfo(resp.message || "A verification code has been sent to your phone.");
        setMfaResendIn(45);
        setStage("mfa");
        setLoading(false);
        return;
      }
      completeLogin(resp);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Sign-in failed.");
      setLoading(false);
    }
  }

  async function handleMfaSubmit(e: FormEvent) {
    e.preventDefault();
    if (!mfaToken) {
      setError("Verification session expired. Please sign in again.");
      setStage("credentials");
      return;
    }
    const code = mfaCode.trim();
    if (!/^\d{4,10}$/.test(code)) {
      setError("Enter the numeric verification code from the SMS.");
      return;
    }
    setError(null);
    setLoading(true);
    try {
      const data = await mfaChallengeVerify(mfaToken, code);
      completeLogin(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Verification failed.");
      setLoading(false);
    }
  }

  async function handleMfaResend() {
    if (!mfaToken || mfaResendIn > 0) return;
    setError(null);
    setMfaInfo(null);
    try {
      const resp = await mfaChallengeSend(mfaToken);
      setMfaInfo(resp.message || "A new verification code has been sent.");
      setMfaResendIn(45);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to resend code.");
    }
  }

  function backToCredentials() {
    setStage("credentials");
    setMfaToken(null);
    setMfaPhone(null);
    setMfaCode("");
    setMfaInfo(null);
    setError(null);
    setLoading(false);
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#0f1f17] via-[#0f5132] to-[#0b3d24] flex items-center justify-center px-4 py-12">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-2xl p-8 sm:p-10">
          <div className="flex flex-col items-center text-center mb-8">
            <div className="w-14 h-14 rounded-2xl bg-[#0f5132] text-white flex items-center justify-center mb-4">
              {stage === "credentials" ? (
                <ShieldCheck className="w-7 h-7" />
              ) : (
                <Smartphone className="w-7 h-7" />
              )}
            </div>
            <h1 className="text-2xl font-bold text-[#0f1f17]">
              {stage === "credentials" ? "Admin Sign In" : "Verify your identity"}
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              {stage === "credentials"
                ? "Enter your administrator credentials to continue."
                : mfaPhone
                ? `Enter the 6-digit code sent to ${mfaPhone}.`
                : "Enter the 6-digit code sent to your phone."}
            </p>
          </div>

          {error && (
            <div
              role="alert"
              className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
            >
              {error}
            </div>
          )}
          {stage === "mfa" && mfaInfo && !error && (
            <div
              role="status"
              className="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700"
            >
              {mfaInfo}
            </div>
          )}

          {stage === "credentials" ? (
            <form onSubmit={handleCredentialsSubmit} className="space-y-5">
              <div>
                <label htmlFor="admin-email" className="block text-sm font-medium text-[#0f1f17] mb-1.5">
                  Email
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    id="admin-email"
                    type="email"
                    autoComplete="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full rounded-lg border border-gray-300 bg-white pl-10 pr-3 py-2.5 text-sm text-[#0f1f17] focus:border-[#0f5132] focus:ring-2 focus:ring-[#0f5132]/20 outline-none transition"
                    placeholder="admin@doiteasy.net"
                  />
                </div>
              </div>

              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <label htmlFor="admin-password" className="block text-sm font-medium text-[#0f1f17]">
                    Password
                  </label>
                  <Link
                    to="/admin/forgot-password"
                    className="text-xs font-medium text-[#0f5132] hover:text-[#0b3d24]"
                  >
                    Forgot password?
                  </Link>
                </div>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    id="admin-password"
                    type={showPassword ? "text" : "password"}
                    autoComplete="current-password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full rounded-lg border border-gray-300 bg-white pl-10 pr-10 py-2.5 text-sm text-[#0f1f17] focus:border-[#0f5132] focus:ring-2 focus:ring-[#0f5132]/20 outline-none transition"
                    placeholder="••••••••"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-[#0f5132] rounded"
                    aria-label={showPassword ? "Hide password" : "Show password"}
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 rounded-lg bg-[#0f5132] hover:bg-[#0b3d24] disabled:opacity-60 disabled:cursor-not-allowed text-white font-semibold py-2.5 text-sm transition"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Signing in…
                  </>
                ) : (
                  <>
                    <LogIn className="w-4 h-4" />
                    Sign in to Admin
                  </>
                )}
              </button>
            </form>
          ) : (
            <form onSubmit={handleMfaSubmit} className="space-y-5">
              <div>
                <label htmlFor="mfa-code" className="block text-sm font-medium text-[#0f1f17] mb-1.5">
                  Verification code
                </label>
                <input
                  id="mfa-code"
                  type="text"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  required
                  maxLength={10}
                  value={mfaCode}
                  onChange={(e) => setMfaCode(e.target.value.replace(/\D+/g, ""))}
                  className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-center text-lg tracking-[0.4em] font-semibold text-[#0f1f17] focus:border-[#0f5132] focus:ring-2 focus:ring-[#0f5132]/20 outline-none transition"
                  placeholder="••••••"
                />
              </div>

              <div className="flex items-center justify-between text-xs">
                <button
                  type="button"
                  onClick={backToCredentials}
                  className="font-medium text-gray-500 hover:text-[#0f5132]"
                >
                  ← Back
                </button>
                <button
                  type="button"
                  onClick={handleMfaResend}
                  disabled={mfaResendIn > 0}
                  className="font-medium text-[#0f5132] hover:text-[#0b3d24] disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {mfaResendIn > 0 ? `Resend code (${mfaResendIn}s)` : "Resend code"}
                </button>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 rounded-lg bg-[#0f5132] hover:bg-[#0b3d24] disabled:opacity-60 disabled:cursor-not-allowed text-white font-semibold py-2.5 text-sm transition"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Verifying…
                  </>
                ) : (
                  <>
                    <ShieldCheck className="w-4 h-4" />
                    Verify and sign in
                  </>
                )}
              </button>
            </form>
          )}

          <div className="mt-6 text-center text-xs text-gray-500">
            Client area?{" "}
            <Link to="/login" className="font-medium text-[#0f5132] hover:text-[#0b3d24]">
              Go to customer login
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}