import { FormEvent, useEffect, useState } from "react";

type LoginPageProps = {
  onAuthenticated: (accessToken: string) => void;
};

const API_BASE = import.meta.env.VITE_API_BASE_URL ?? "/api/v1";

export function LoginPage({ onAuthenticated }: LoginPageProps) {
  const [mode, setMode] = useState<"login" | "bootstrap">("login");
  const [username, setUsername] = useState("admin");
  const [displayName, setDisplayName] = useState("NexaVPN Admin");
  const [password, setPassword] = useState("admin123!");
  const [bootstrapAvailable, setBootstrapAvailable] = useState(false);
  const [bootstrapStatusLoaded, setBootstrapStatusLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;

    void fetch(`${API_BASE}/auth/bootstrap/status`)
      .then(async (response) => {
        if (!response.ok) {
          throw new Error(`Bootstrap status failed: ${response.status}`);
        }
        return response.json() as Promise<{ bootstrap_available: boolean }>;
      })
      .then((payload) => {
        if (cancelled) {
          return;
        }
        setBootstrapAvailable(payload.bootstrap_available);
        if (!payload.bootstrap_available) {
          setMode("login");
        }
      })
      .catch(() => {
        if (!cancelled) {
          setBootstrapAvailable(false);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setBootstrapStatusLoaded(true);
        }
      });

    return () => {
      cancelled = true;
    };
  }, []);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    setLoading(true);
    setError(null);

    try {
      if (mode === "bootstrap") {
        const bootstrap = await fetch(`${API_BASE}/auth/bootstrap`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            username,
            display_name: displayName,
            password
          })
        });

        if (!bootstrap.ok && bootstrap.status !== 409) {
          throw new Error(`Bootstrap failed: ${bootstrap.status}`);
        }
      }

      const login = await fetch(`${API_BASE}/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password })
      });

      if (!login.ok) {
        throw new Error("Login failed");
      }

      const payload = (await login.json()) as { access_token: string };
      onAuthenticated(payload.access_token);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Authentication failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="auth-shell">
      <form className="auth-card" onSubmit={onSubmit}>
        <div className="auth-brand">
          <img className="brand-logo brand-logo-full" src="/NexaVPN_Logo.png" alt="NexaVPN" />
          <div className="auth-brand-copy">
            <p className="eyebrow">NexaVPN Admin</p>
            <h2>{mode === "login" ? "Sign in" : "Create initial admin"}</h2>
          </div>
        </div>
        <p className="auth-copy">
          {mode === "login"
            ? "Use your NexaVPN admin credentials."
            : "Bootstrap the first admin account for a fresh deployment."}
        </p>
        <label>
          Username
          <input value={username} onChange={(event) => setUsername(event.target.value)} />
        </label>
        {mode === "bootstrap" ? (
          <label>
            Display name
            <input value={displayName} onChange={(event) => setDisplayName(event.target.value)} />
          </label>
        ) : null}
        <label>
          Password
          <input type="password" value={password} onChange={(event) => setPassword(event.target.value)} />
        </label>
        {error ? <p className="notice">{error}</p> : null}
        <button className="button" disabled={loading} type="submit">
          {loading ? "Please wait..." : mode === "login" ? "Sign in" : "Bootstrap and sign in"}
        </button>
        {bootstrapStatusLoaded && bootstrapAvailable ? (
          <button
            className="ghost-button"
            type="button"
            onClick={() => setMode((current) => (current === "login" ? "bootstrap" : "login"))}
          >
            {mode === "login" ? "Need initial setup?" : "Already have an admin?"}
          </button>
        ) : null}
      </form>
    </div>
  );
}
