import { useState, useEffect } from "react";

const VALID_CODE = "E1GU-NB3K"; // einer der 8 Recovery-Codes aus OB-04
const MAX_ATTEMPTS = 5;

export default function TA02() {
  const [code, setCode]           = useState("");
  const [attempts, setAttempts]   = useState(0);
  const [error, setError]         = useState("");
  const [locked, setLocked]       = useState(false);
  const [lockRemaining, setLockRemaining] = useState(900);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (!locked) return;
    if (lockRemaining <= 0) { setLocked(false); setAttempts(0); setError(""); return; }
    const t = setTimeout(() => setLockRemaining(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [locked, lockRemaining]);

  const formatTime = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;

  const handleSubmit = () => {
    if (locked || !code.trim()) return;
    const normalized = code.trim().toUpperCase();
    if (normalized === VALID_CODE) {
      setSubmitted(true);
    } else {
      const next = attempts + 1;
      setAttempts(next);
      if (next >= MAX_ATTEMPTS) {
        setLocked(true);
        setLockRemaining(900);
        setError("Zu viele Fehlversuche. Bitte warten Sie 15 Minuten.");
      } else {
        setError(`Ungültiger oder bereits verwendeter Code. Noch ${MAX_ATTEMPTS - next} Versuch${MAX_ATTEMPTS - next === 1 ? "" : "e"} übrig.`);
      }
      setCode("");
    }
  };

  if (submitted) {
    return (
      <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 400, borderRadius: 8, overflow: "hidden" }}>
        <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
          <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 350, padding: 24 }}>
          <div style={{ textAlign: "center", maxWidth: 400 }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#FAEEDA", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 24, marginBottom: 16 }}>⚠</div>
            <div style={{ fontSize: 18, fontWeight: 500, color: "#1a1a18", marginBottom: 8 }}>Login erfolgreich — 2FA neu einrichten</div>
            <div style={{ background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, padding: "12px 16px", fontSize: 12, color: "#BA7517", marginBottom: 20, textAlign: "left" }}>
              Der verwendete Recovery-Code ist jetzt ungültig. Sie müssen eine neue 2FA-App einrichten, bevor Sie fortfahren können.
            </div>
            <button onClick={() => alert("→ OB-03: Neue 2FA einrichten")}
              style={{ padding: "10px 28px", fontSize: 13, fontWeight: 500, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer" }}>
              Neue 2FA einrichten →
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 500, borderRadius: 8, overflow: "hidden" }}>

      {/* NAV (öffentlich, minimal) */}
      <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
        <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
        <span style={{ fontSize: 11, color: "#888780" }}>Anmeldung</span>
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px" }}>
        <div style={{ width: "100%", maxWidth: 440 }}>

          {/* TITEL */}
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#FAEEDA", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 26, marginBottom: 12 }}>🔑</div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, marginBottom: 6 }}>
              <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Login mit Recovery-Code</h1>
              <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>TA-02</span>
            </div>
            <p style={{ fontSize: 12, color: "#5F5E5A", margin: 0 }}>2FA-Gerät nicht verfügbar? Geben Sie einen Ihrer gespeicherten Recovery-Codes ein.</p>
          </div>

          {/* FORMULAR CARD */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 10, padding: "24px", marginBottom: 16 }}>

            {/* WARN-BANNER */}
            <div style={{ background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#BA7517", marginBottom: 20 }}>
              ⚠ Jeder Recovery-Code kann nur <strong>einmal</strong> verwendet werden. Nach der Verwendung wird er automatisch ungültig. Danach müssen Sie eine neue 2FA-App einrichten.
            </div>

            {/* Sperre-Banner */}
            {locked && (
              <div style={{ background: "#FCEBEB", border: "1px solid #F7C1C1", borderRadius: 6, padding: "12px 16px", fontSize: 12, color: "#A32D2D", marginBottom: 16, textAlign: "center" }}>
                <div style={{ fontWeight: 500, marginBottom: 6 }}>Zu viele Fehlversuche ({MAX_ATTEMPTS}/{MAX_ATTEMPTS}). Bitte warten:</div>
                <div style={{ fontSize: 24, fontWeight: 700, fontFamily: "monospace" }}>{formatTime(lockRemaining)}</div>
              </div>
            )}

            {/* Code-Eingabe */}
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18", marginBottom: 6 }}>
                Recovery-Code <span style={{ color: "#A32D2D" }}>*</span>
              </label>
              <input
                value={code}
                onChange={e => { if (!locked) { setCode(e.target.value.toUpperCase()); setError(""); } }}
                onKeyDown={e => e.key === "Enter" && handleSubmit()}
                placeholder="z.B. E1GU-NB3K"
                disabled={locked}
                style={{ width: "100%", boxSizing: "border-box", padding: "10px 14px", fontSize: 15, fontFamily: "monospace", letterSpacing: 2, textAlign: "center", border: `1px solid ${error ? "#A32D2D" : "#B4B2A9"}`, borderRadius: 6, background: locked ? "#F1EFE8" : "#fff", outline: "none", textTransform: "uppercase" }}
              />
              {error && !locked && (
                <div style={{ fontSize: 11, color: "#A32D2D", marginTop: 6 }}>⚠ {error}</div>
              )}
              {attempts > 0 && !locked && (
                <div style={{ fontSize: 10, color: "#888780", marginTop: 4, textAlign: "right" }}>Versuche: {attempts}/{MAX_ATTEMPTS}</div>
              )}
              <div style={{ fontSize: 10, color: "#888780", marginTop: 6 }}>
                Format: XXXX-XXXX (8 Zeichen, Grossbuchstaben und Ziffern)
              </div>
              <div style={{ fontSize: 10, color: "#888780", marginTop: 2 }}>
                Tipp für Simulation: Code <strong>E1GU-NB3K</strong> ist gültig. Andere Codes simulieren F8.
              </div>
            </div>

            {/* BUTTON */}
            <button onClick={handleSubmit} disabled={!code.trim() || locked}
              style={{ width: "100%", padding: "11px", fontSize: 13, fontWeight: 500,
                background: code.trim() && !locked ? "#185FA5" : "#D3D1C7",
                border: "none", borderRadius: 6, color: "#fff",
                cursor: code.trim() && !locked ? "pointer" : "not-allowed" }}>
              Code einlösen & anmelden →
            </button>

          </div>

          {/* ZURÜCK ZUR 2FA */}
          <div style={{ textAlign: "center", fontSize: 12 }}>
            <span style={{ color: "#888780" }}>2FA-Gerät wieder verfügbar? </span>
            <span style={{ color: "#185FA5", cursor: "pointer" }} onClick={() => alert("→ Standard 2FA-Login")}>
              Zurück zur 2FA-Eingabe
            </span>
          </div>

          {/* SUPERADMIN-HINWEIS */}
          <div style={{ marginTop: 16, background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#5F5E5A" }}>
            Alle Recovery-Codes verloren? Kontaktieren Sie Ihren DiveLogix360-Administrator für einen Superadmin-Reset (A6).
          </div>

          {/* METAINFO */}
          <div style={{ marginTop: 12, padding: "8px 12px", background: "#fff", border: "1px solid #D3D1C7", borderRadius: 6, fontSize: 10, color: "#888780" }}>
            Screen: TA-02  |  UC00 – Tenant-Onboarding  |  Akteur: tenant_admin  |  Alternativpfad A5  |  v0.1 – April 2026
          </div>

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