import { useState, type FormEvent } from "react";
import { BRAND, login, verifyTotp } from "../api.js";

export function LoginPage({ onLogin }: { onLogin: () => void }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  // 2FA-steget: sätts när kontot har TOTP aktiverat.
  const [preAuthToken, setPreAuthToken] = useState<string | null>(null);
  const [code, setCode] = useState("");

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const result = await login(email, password);
      if (result.totpRequired && result.preAuthToken) {
        setPreAuthToken(result.preAuthToken);
      } else {
        onLogin();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Inloggningen misslyckades.");
    } finally {
      setBusy(false);
    }
  };

  const submitCode = async (e: FormEvent) => {
    e.preventDefault();
    if (!preAuthToken) return;
    setBusy(true);
    setError(null);
    try {
      await verifyTotp(preAuthToken, code);
      onLogin();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Fel engångskod.");
    } finally {
      setBusy(false);
    }
  };

  if (preAuthToken) {
    return (
      <div className="login-wrap">
        <form className="login-box" onSubmit={submitCode}>
          <h1>Tvåfaktorsautentisering</h1>
          <p className="muted">Ange den sexsiffriga koden från din autentiseringsapp.</p>
          <input
            inputMode="numeric"
            autoComplete="one-time-code"
            placeholder="000000"
            maxLength={6}
            value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
            autoFocus
            required
          />
          {error && <div className="error-text">{error}</div>}
          <button className="primary" disabled={busy || code.length !== 6}>
            {busy ? "Verifierar …" : "Verifiera"}
          </button>
          <button
            type="button"
            className="ghost"
            onClick={() => {
              setPreAuthToken(null);
              setCode("");
              setError(null);
            }}
          >
            Avbryt
          </button>
        </form>
      </div>
    );
  }

  return (
    <div className="login-wrap">
      <form className="login-box" onSubmit={submit}>
        <h1>{BRAND.name} Admin</h1>
        <input
          type="email"
          placeholder="E-post"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <input
          type="password"
          placeholder="Lösenord"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
        {error && <div className="error-text">{error}</div>}
        <button className="primary" disabled={busy}>
          {busy ? "Loggar in …" : "Logga in"}
        </button>
        <div className="muted">Kräver konto med admin-roll.</div>
      </form>
    </div>
  );
}
