import { useState } from "react";

const TENANT = {
  slug: "k7x2m9pq",
  name: "Tauchschule Zürich GmbH",
  country: "CH",
  plan: "Professional",
  status: "aktiv",
  admin: { name: "Hans Muster", email: "inhaber@tauchzh.ch", tfa: true, lastLogin: "21.04.2026 14:32" },
  address: { street: "Seestrasse 12", zip: "8001", city: "Zürich" },
  currency: "CHF",
  created: "12.03.2026",
  onboarding: { tokenStatus: "used", profileComplete: true },
};

const PLAN_COLORS = {
  "Test":         { bg: "#F1EFE8", color: "#5F5E5A" },
  "Starter":      { bg: "#E6F1FB", color: "#185FA5" },
  "Professional": { bg: "#EEEDFE", color: "#534AB7" },
  "Enterprise":   { bg: "#EAF3DE", color: "#3B6D11" },
};

const PLANS = ["Test", "Starter", "Professional", "Enterprise"];

const DEACTIVATE_REASONS = [
  "Zahlung ausstehend / nicht bezahlt",
  "Vertrag gekündigt",
  "Missbrauch / Verstoss gegen AGB",
  "Auf Wunsch des Kunden",
  "Test-Phase abgelaufen – kein Upgrade",
  "Anderer Grund (siehe unten)",
];

export default function SA03() {
  const [tenant, setTenant] = useState(TENANT);

  // Dialog-States
  const [dialog, setDialog] = useState(null); // 'deactivate' | 'plan' | '2fa-reset'

  // Deaktivieren
  const [deactivateReason, setDeactivateReason] = useState("");
  const [deactivateCustom, setDeactivateCustom] = useState("");

  // Plan ändern
  const [selectedPlan, setSelectedPlan] = useState(tenant.plan);
  const [planNote, setPlanNote] = useState("");

  // 2FA-Reset
  const [tfaConfirmed, setTfaConfirmed] = useState(false);

  const closeDialog = () => {
    setDialog(null);
    setDeactivateReason("");
    setDeactivateCustom("");
    setSelectedPlan(tenant.plan);
    setPlanNote("");
    setTfaConfirmed(false);
  };

  const canDeactivate = deactivateReason &&
    (deactivateReason !== "Anderer Grund (siehe unten)" || deactivateCustom.trim());

  const canChangePlan = selectedPlan !== tenant.plan;

  const handleDeactivate = () => {
    setTenant(t => ({ ...t, status: "inaktiv" }));
    closeDialog();
  };

  const handlePlanChange = () => {
    setTenant(t => ({ ...t, plan: selectedPlan }));
    closeDialog();
  };

  const handleTfaReset = () => {
    alert(`2FA-Reset für ${tenant.admin.email} ausgelöst. E-Mail-Benachrichtigung gesendet.`);
    closeDialog();
  };

  const handleResendInvite = () => {
    alert(`Einladung erneut gesendet an ${tenant.admin.email}`);
  };

  const handleActivate = () => {
    setTenant(t => ({ ...t, status: "aktiv" }));
  };

  const st = tenant.status === "aktiv"
    ? { bg: "#EAF3DE", color: "#3B6D11", label: "Aktiv" }
    : { bg: "#F1EFE8", color: "#5F5E5A", label: "Inaktiv" };

  const pc = PLAN_COLORS[tenant.plan];

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

      {/* NAV */}
      <div style={{ background: "#1a1a18", padding: "10px 20px", fontSize: 13, display: "flex", alignItems: "center", gap: 16, borderRadius: "8px 8px 0 0" }}>
        <span style={{ fontWeight: 700, color: "#fff" }}>DiveLogix360</span>
        <span style={{ color: "#5F5E5A" }}>|</span>
        <span style={{ color: "#888780" }}>Superadmin-Panel</span>
        <div style={{ marginLeft: "auto", display: "flex", gap: 16, fontSize: 12 }}>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>Tenants</span>
          <span style={{ color: "#888780" }}>Benutzer</span>
          <span style={{ color: "#888780" }}>System</span>
          <span style={{ color: "#D3D1C7", fontWeight: 500 }}>SA · Admin</span>
        </div>
      </div>

      <div style={{ padding: "16px 24px" }}>

        {/* BREADCRUMB */}
        <div style={{ fontSize: 12, color: "#888780", marginBottom: 12 }}>
          <span style={{ color: "#185FA5", cursor: "pointer" }}>Tenants</span>
          <span style={{ margin: "0 6px" }}>›</span>
          <span>{tenant.name}</span>
        </div>

        {/* ── ONBOARDING-STATUS BANNER ── */}
        {(!tenant.onboarding.profileComplete || tenant.onboarding.tokenStatus === "pending") && (
          <div style={{ background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, padding: "10px 16px", marginBottom: 16, fontSize: 12, color: "#BA7517", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span>
              ⚠ <strong>Onboarding nicht abgeschlossen:</strong>{" "}
              {tenant.onboarding.tokenStatus === "pending" && "Einladungs-Token noch offen (nicht geöffnet). "}
              {!tenant.onboarding.profileComplete && "Schulprofil unvollständig."}
            </span>
            <button onClick={handleResendInvite}
              style={{ fontSize: 11, padding: "4px 10px", background: "#fff", border: "1px solid #FAC775", borderRadius: 5, color: "#BA7517", cursor: "pointer" }}>
              Einladung erneut senden
            </button>
          </div>
        )}

        {/* ── MODAL DIALOGE ── */}
        {dialog && (
          <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.45)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100 }}>
            <div style={{ background: "#fff", borderRadius: 10, padding: "24px 28px", width: 480, boxShadow: "0 8px 32px rgba(0,0,0,0.18)" }}>

              {/* ── DIALOG: DEAKTIVIEREN ── */}
              {dialog === "deactivate" && (
                <>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                    <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#FCEBEB", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>⚠</div>
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 500 }}>Tenant deaktivieren</div>
                      <div style={{ fontSize: 12, color: "#A32D2D" }}>{tenant.name}</div>
                    </div>
                  </div>
                  <div style={{ background: "#FCEBEB", border: "1px solid #F7C1C1", borderRadius: 6, padding: "10px 14px", fontSize: 12, color: "#A32D2D", marginBottom: 14 }}>
                    Alle Benutzer verlieren <strong>sofort</strong> den Zugriff. Eine Bestätigungs-E-Mail wird an den Tenant-Admin gesendet (BCC an SuperAdmin).
                  </div>
                  <div style={{ marginBottom: 12 }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 6 }}>Grund der Deaktivierung <span style={{ color: "#A32D2D" }}>*</span></label>
                    <select value={deactivateReason} onChange={e => setDeactivateReason(e.target.value)}
                      style={{ width: "100%", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff" }}>
                      <option value="">— Grund wählen —</option>
                      {DEACTIVATE_REASONS.map(r => <option key={r}>{r}</option>)}
                    </select>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 6 }}>
                      Zusätzliche Angaben
                      {deactivateReason === "Anderer Grund (siehe unten)" && <span style={{ color: "#A32D2D" }}> *</span>}
                    </label>
                    <textarea value={deactivateCustom} onChange={e => setDeactivateCustom(e.target.value)}
                      rows={3} placeholder="Optionale Zusatzinformation..."
                      style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, resize: "none" }} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                    <button onClick={closeDialog} style={{ padding: "8px 16px", fontSize: 12, background: "transparent", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>Abbrechen</button>
                    <button onClick={handleDeactivate} disabled={!canDeactivate}
                      style={{ padding: "8px 16px", fontSize: 12, background: canDeactivate ? "#A32D2D" : "#D3D1C7", border: "none", borderRadius: 6, color: "#fff", cursor: canDeactivate ? "pointer" : "not-allowed", fontWeight: 500 }}>
                      Deaktivieren & E-Mail senden
                    </button>
                  </div>
                </>
              )}

              {/* ── DIALOG: PLAN ÄNDERN ── */}
              {dialog === "plan" && (
                <>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                    <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#E6F1FB", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>📋</div>
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 500 }}>Plan ändern</div>
                      <div style={{ fontSize: 12, color: "#5F5E5A" }}>{tenant.name}</div>
                    </div>
                  </div>
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 12, color: "#888780", marginBottom: 8 }}>Aktueller Plan:</div>
                    <span style={{ background: pc.bg, color: pc.color, fontSize: 12, padding: "3px 10px", borderRadius: 20, fontWeight: 500 }}>{tenant.plan}</span>
                  </div>
                  <div style={{ marginBottom: 14 }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 8 }}>Neuer Plan <span style={{ color: "#A32D2D" }}>*</span></label>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                      {PLANS.map(p => {
                        const c = PLAN_COLORS[p];
                        const isSelected = selectedPlan === p;
                        return (
                          <div key={p} onClick={() => setSelectedPlan(p)}
                            style={{ border: `2px solid ${isSelected ? c.color : "#D3D1C7"}`, borderRadius: 8, padding: "10px 14px", cursor: "pointer", background: isSelected ? c.bg : "#fff" }}>
                            <div style={{ fontWeight: 500, color: c.color, fontSize: 13 }}>{p}</div>
                            {p === tenant.plan && <div style={{ fontSize: 10, color: "#888780", marginTop: 2 }}>aktuell</div>}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 6 }}>Notiz / Begründung</label>
                    <textarea value={planNote} onChange={e => setPlanNote(e.target.value)}
                      rows={2} placeholder="Optional: Grund für die Planänderung..."
                      style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, resize: "none" }} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                    <button onClick={closeDialog} style={{ padding: "8px 16px", fontSize: 12, background: "transparent", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>Abbrechen</button>
                    <button onClick={handlePlanChange} disabled={!canChangePlan}
                      style={{ padding: "8px 16px", fontSize: 12, background: canChangePlan ? "#185FA5" : "#D3D1C7", border: "none", borderRadius: 6, color: "#fff", cursor: canChangePlan ? "pointer" : "not-allowed", fontWeight: 500 }}>
                      Plan ändern & speichern
                    </button>
                  </div>
                </>
              )}

              {/* ── DIALOG: 2FA-RESET ── */}
              {dialog === "2fa-reset" && (
                <>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                    <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#FAEEDA", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>🔐</div>
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 500 }}>2FA zurücksetzen</div>
                      <div style={{ fontSize: 12, color: "#5F5E5A" }}>{tenant.admin.email}</div>
                    </div>
                  </div>
                  <div style={{ background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 6, padding: "10px 14px", fontSize: 12, color: "#BA7517", marginBottom: 16 }}>
                    Der Tenant-Admin verliert den 2FA-Schutz temporär. Er muss beim nächsten Login eine neue 2FA-App einrichten. Eine Benachrichtigungs-E-Mail wird automatisch gesendet (Template: <code>2fa_reset / de</code>).
                  </div>
                  <label style={{ display: "flex", alignItems: "flex-start", gap: 10, fontSize: 12, cursor: "pointer", marginBottom: 20 }}>
                    <input type="checkbox" checked={tfaConfirmed} onChange={e => setTfaConfirmed(e.target.checked)} style={{ marginTop: 2 }} />
                    Ich bestätige, dass ich den 2FA-Reset für diesen Benutzer bewusst ausführe und der Benutzer darüber informiert wurde.
                  </label>
                  <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                    <button onClick={closeDialog} style={{ padding: "8px 16px", fontSize: 12, background: "transparent", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>Abbrechen</button>
                    <button onClick={handleTfaReset} disabled={!tfaConfirmed}
                      style={{ padding: "8px 16px", fontSize: 12, background: tfaConfirmed ? "#BA7517" : "#D3D1C7", border: "none", borderRadius: 6, color: "#fff", cursor: tfaConfirmed ? "pointer" : "not-allowed", fontWeight: 500 }}>
                      2FA zurücksetzen & E-Mail senden
                    </button>
                  </div>
                </>
              )}

            </div>
          </div>
        )}

        {/* ── HEADER: Titel + Status + Aktionen ── */}
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 16 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>{tenant.name}</h1>
              <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>SA-03</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12 }}>
              <span style={{ fontFamily: "monospace", color: "#888780" }}>{tenant.slug}</span>
              <span style={{ color: "#D3D1C7" }}>·</span>
              <span style={{ background: st.bg, color: st.color, fontWeight: 500, padding: "2px 8px", borderRadius: 20, fontSize: 11 }}>{st.label}</span>
              <span style={{ background: pc.bg, color: pc.color, padding: "2px 8px", borderRadius: 20, fontSize: 11 }}>{tenant.plan}</span>
              <span style={{ color: "#888780" }}>Erstellt: {tenant.created}</span>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setDialog("plan")}
              style={{ fontSize: 12, padding: "7px 14px", background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>
              Plan ändern
            </button>
            {tenant.status === "aktiv"
              ? <button onClick={() => setDialog("deactivate")}
                  style={{ fontSize: 12, padding: "7px 14px", background: "#FCEBEB", border: "1px solid #A32D2D", borderRadius: 6, color: "#A32D2D", cursor: "pointer", fontWeight: 500 }}>
                  Deaktivieren
                </button>
              : <button onClick={handleActivate}
                  style={{ fontSize: 12, padding: "7px 14px", background: "#EAF3DE", border: "1px solid #3B6D11", borderRadius: 6, color: "#3B6D11", cursor: "pointer", fontWeight: 500 }}>
                  Aktivieren
                </button>
            }
          </div>
        </div>

        {/* ── ZWEISPALTIGES LAYOUT ── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>

          {/* STAMMDATEN */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px" }}>
            <div style={{ fontSize: 11, fontWeight: 500, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>Stammdaten</div>
            {[
              ["Schulname", tenant.name],
              ["Land", tenant.country],
              ["Adresse", `${tenant.address.street}, ${tenant.address.zip} ${tenant.address.city}`],
              ["Währung", tenant.currency],
              ["Erstellt am", tenant.created],
            ].map(([label, value]) => (
              <div key={label} style={{ display: "flex", alignItems: "center", fontSize: 12, marginBottom: 8, paddingBottom: 8, borderBottom: "1px solid #F1EFE8" }}>
                <span style={{ color: "#888780", minWidth: 110 }}>{label}</span>
                <span style={{ color: "#1a1a18" }}>{value}</span>
              </div>
            ))}
          </div>

          {/* PLAN & STATUS */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px" }}>
            <div style={{ fontSize: 11, fontWeight: 500, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>Plan & Status</div>
            {[
              ["Plan-Typ", <span style={{ background: pc.bg, color: pc.color, padding: "1px 8px", borderRadius: 20, fontSize: 11 }}>{tenant.plan}</span>],
              ["Status", <span style={{ background: st.bg, color: st.color, padding: "1px 8px", borderRadius: 20, fontSize: 11, fontWeight: 500 }}>{st.label}</span>],
              ["Onboarding", <span style={{ color: tenant.onboarding.profileComplete ? "#3B6D11" : "#BA7517" }}>{tenant.onboarding.profileComplete ? "✓ Abgeschlossen" : "⚠ Unvollständig"}</span>],
              ["Token", <span style={{ color: tenant.onboarding.tokenStatus === "used" ? "#3B6D11" : "#BA7517" }}>{tenant.onboarding.tokenStatus === "used" ? "✓ Eingelöst" : "Offen (noch gültig)"}</span>],
            ].map(([label, value]) => (
              <div key={label} style={{ display: "flex", alignItems: "center", fontSize: 12, marginBottom: 8, paddingBottom: 8, borderBottom: "1px solid #F1EFE8" }}>
                <span style={{ color: "#888780", minWidth: 110 }}>{label}</span>
                <span>{value}</span>
              </div>
            ))}
          </div>

          {/* TENANT-ADMIN (Benutzer) */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px", gridColumn: "1 / -1" }}>
            <div style={{ fontSize: 11, fontWeight: 500, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>Tenant-Admin (Benutzer)</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto", alignItems: "start", gap: 16 }}>
              <div>
                {[
                  ["Name", tenant.admin.name],
                  ["E-Mail", tenant.admin.email],
                  ["2FA", tenant.admin.tfa ? "✓ Aktiv" : "⚠ Nicht eingerichtet"],
                  ["Letzter Login", tenant.admin.lastLogin],
                ].map(([label, value]) => (
                  <div key={label} style={{ display: "flex", alignItems: "center", fontSize: 12, marginBottom: 8, paddingBottom: 8, borderBottom: "1px solid #F1EFE8" }}>
                    <span style={{ color: "#888780", minWidth: 110 }}>{label}</span>
                    <span style={{ color: label === "2FA" && tenant.admin.tfa ? "#3B6D11" : "#1a1a18" }}>{value}</span>
                  </div>
                ))}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8, paddingTop: 2 }}>
                <button onClick={() => setDialog("2fa-reset")}
                  style={{ fontSize: 11, padding: "6px 12px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 6, color: "#BA7517", cursor: "pointer", whiteSpace: "nowrap" }}>
                  🔐 2FA zurücksetzen
                </button>
                <button onClick={handleResendInvite}
                  style={{ fontSize: 11, padding: "6px 12px", background: "#F1EFE8", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer", whiteSpace: "nowrap" }}>
                  Einladung erneut senden
                </button>
              </div>
            </div>
          </div>

        </div>

        {/* SIMULATIONSHINWEIS */}
        <div style={{ marginTop: 14, padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> "Plan ändern" → Modal mit Plan-Auswahl. "Deaktivieren/Aktivieren" → Dialog mit Grund. "2FA zurücksetzen" → Bestätigungs-Dialog mit Checkbox.
        </div>
      </div>
    </div>
  );
}
