import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { ChevronDown, ChevronUp, ShieldAlert, Building2, Loader2 } from "lucide-react";
import { useAuth } from "../context/AuthContext";
import { getSsoStatus } from "../api/sso";

export default function LoginPage() {
  const { login, isAuthenticated } = useAuth();
  const navigate = useNavigate();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [emergencyOpen, setEmergencyOpen] = useState(false);

  // Fetch SSO status to determine which login method to show
  const { data: ssoStatus, isLoading: ssoLoading } = useQuery({
    queryKey: ["sso-status"],
    queryFn: getSsoStatus,
    retry: false,
    staleTime: 30_000,
  });

  const ssoActive = ssoStatus?.enabled && ssoStatus?.configured;

  // If already logged in, redirect immediately
  if (isAuthenticated) {
    navigate("/dashboard", { replace: true });
    return null;
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      await login(username, password);
      navigate("/dashboard", { replace: true });
    } catch {
      setError("Invalid username or password");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-950 px-4">
      <div className="w-full max-w-sm space-y-8">
        {/* Logo */}
        <div className="flex flex-col items-center gap-3">
          <img src="/aegis-logo.png" alt="Aegis" className="h-16 w-16 rounded-full" />
          <h1 className="text-2xl font-bold tracking-wide text-white">Aegis</h1>
          <p className="text-sm text-gray-400">MITRE ATT&CK Coverage Platform</p>
        </div>

        {ssoLoading ? (
          /* Loading SSO status */
          <div className="flex justify-center py-6">
            <Loader2 className="h-6 w-6 animate-spin text-cyan-400" />
          </div>
        ) : ssoActive ? (
          /* ── SSO primary login ───────────────────────────────────── */
          <div className="space-y-5">
            {/* Primary: Azure SSO button */}
            <a
              href="/api/v1/sso/login"
              className="flex w-full items-center justify-center gap-3 rounded-lg bg-[#0078d4] px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-[#106ebe] focus:outline-none focus:ring-2 focus:ring-[#0078d4]/50"
            >
              <Building2 className="h-5 w-5" />
              Sign in with {ssoStatus?.provider_name || "Azure AD"}
            </a>

            <p className="text-center text-xs text-gray-500">
              Use your corporate credentials — managed by your IT team
            </p>

            {/* Emergency local login (collapsible) */}
            <div className="rounded-lg border border-gray-800 bg-gray-900/60">
              <button
                type="button"
                onClick={() => setEmergencyOpen(!emergencyOpen)}
                className="flex w-full items-center justify-between rounded-lg px-4 py-3 text-left transition-colors hover:bg-gray-800/40"
              >
                <div className="flex items-center gap-2">
                  <ShieldAlert className="h-4 w-4 text-yellow-500" />
                  <span className="text-sm font-medium text-yellow-400">
                    Emergency admin access
                  </span>
                </div>
                {emergencyOpen ? (
                  <ChevronUp className="h-4 w-4 text-gray-500" />
                ) : (
                  <ChevronDown className="h-4 w-4 text-gray-500" />
                )}
              </button>

              {emergencyOpen && (
                <div className="border-t border-gray-800 px-4 pb-4 pt-3">
                  <p className="mb-3 text-xs text-gray-500">
                    Local login — only for emergency admin access when SSO is unavailable.
                  </p>
                  <form onSubmit={handleSubmit} className="space-y-3">
                    <input
                      type="text"
                      required
                      autoFocus
                      value={username}
                      onChange={(e) => setUsername(e.target.value)}
                      placeholder="Username"
                      className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-white placeholder-gray-500 outline-none focus:border-cyan-500 focus:ring-1 focus:ring-cyan-500"
                    />
                    <input
                      type="password"
                      required
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="Password"
                      className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-white placeholder-gray-500 outline-none focus:border-cyan-500 focus:ring-1 focus:ring-cyan-500"
                    />
                    {error && (
                      <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-400">
                        {error}
                      </p>
                    )}
                    <button
                      type="submit"
                      disabled={loading}
                      className="w-full rounded-lg bg-gray-700 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-600 disabled:opacity-50"
                    >
                      {loading ? "Signing in…" : "Sign in locally"}
                    </button>
                  </form>
                </div>
              )}
            </div>
          </div>
        ) : (
          /* ── Local login (SSO not configured) ───────────────────── */
          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label
                htmlFor="username"
                className="mb-1.5 block text-sm font-medium text-gray-300"
              >
                Username
              </label>
              <input
                id="username"
                type="text"
                required
                autoFocus
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-sm text-white placeholder-gray-500 outline-none focus:border-cyan-500 focus:ring-1 focus:ring-cyan-500"
                placeholder="admin"
              />
            </div>

            <div>
              <label
                htmlFor="password"
                className="mb-1.5 block text-sm font-medium text-gray-300"
              >
                Password
              </label>
              <input
                id="password"
                type="password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-sm text-white placeholder-gray-500 outline-none focus:border-cyan-500 focus:ring-1 focus:ring-cyan-500"
                placeholder="••••••••"
              />
            </div>

            {error && (
              <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-400">
                {error}
              </p>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-lg bg-cyan-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-cyan-500 disabled:opacity-50"
            >
              {loading ? "Signing in…" : "Sign in"}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
