import { useState } from "react";

const TENANTS = [
  { slug: "k7x2m9pq", name: "Tauchschule Zürich GmbH",  country: "CH", plan: "Professional", status: "aktiv",           admin: "inhaber@tauchzh.ch",  created: "12.03.2026", trial: null },
  { slug: "b3r8t1nw", name: "Dive Center Berlin",        country: "DE", plan: "Starter",      status: "aktiv",           admin: "info@divebln.de",     created: "28.03.2026", trial: null },
  { slug: "x9q4p2lm", name: "Tauchclub Innsbruck",       country: "AT", plan: "Test",         status: "test",            admin: "club@tauch-ibk.at",   created: "18.04.2026", trial: "28.04.2026" },
  { slug: "m5k7r3vc", name: "Scuba World Basel",         country: "CH", plan: "Enterprise",   status: "aktiv",           admin: "admin@scubaworld.ch", created: "05.01.2026", trial: null },
  { slug: "n2w6s8qp", name: "Taucherclub Hamburg",       country: "DE", plan: "Starter",      status: "inaktiv",         admin: "kontakt@tc-hh.de",    created: "15.11.2025", trial: null },
  { slug: "p4f1h9zt", name: "Blue Ocean Genf",           country: "CH", plan: "Test",         status: "test-abgelaufen", admin: "info@blueocean.ch",   created: "01.03.2026", trial: "31.03.2026" },
];

const STATUS_STYLES = {
  "aktiv":           { bg: "#EAF3DE", color: "#3B6D11", label: "Aktiv" },
  "test":            { bg: "#FAEEDA", color: "#BA7517", label: "Test" },
  "test-abgelaufen": { bg: "#FCEBEB", color: "#A32D2D", label: "Test abgelaufen" },
  "inaktiv":         { bg: "#F1EFE8", color: "#5F5E5A", label: "Inaktiv" },
};

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

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 SA01() {
  const [search, setSearch]               = useState("");
  const [filterStatus, setFilterStatus]   = useState("alle");
  const [filterPlan, setFilterPlan]       = useState("alle");
  const [selectedSlug, setSelectedSlug]   = useState(null);
  const [deactivateTarget, setDeactivateTarget] = useState(null);
  const [deactivateReason, setDeactivateReason] = useState("");
  const [deactivateCustom, setDeactivateCustom] = useState("");

  const filtered = TENANTS.filter(t => {
    const matchSearch = t.name.toLowerCase().includes(search.toLowerCase()) ||
                        t.admin.toLowerCase().includes(search.toLowerCase()) ||
                        t.slug.includes(search.toLowerCase());
    const matchStatus = filterStatus === "alle" || t.status === filterStatus;
    const matchPlan   = filterPlan   === "alle" || t.plan   === filterPlan;
    return matchSearch && matchStatus && matchPlan;
  });

  const closeDialog = () => {
    setDeactivateTarget(null);
    setDeactivateReason("");
    setDeactivateCustom("");
  };

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

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 600, 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: "20px 24px" }}>

        {/* DEAKTIVIERUNGS-DIALOG */}
        {deactivateTarget && (
          <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)" }}>
              <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, color: "#1a1a18" }}>Tenant deaktivieren</div>
                  <div style={{ fontSize: 12, color: "#A32D2D" }}>{deactivateTarget.name}</div>
                </div>
              </div>
              <div style={{ background: "#FCEBEB", border: "1px solid #F7C1C1", borderRadius: 6, padding: "10px 14px", fontSize: 12, color: "#A32D2D", marginBottom: 16 }}>
                Alle Benutzer dieses Tenants 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, color: "#1a1a18", 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", outline: "none" }}>
                  <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, color: "#1a1a18", marginBottom: 6 }}>
                  Zusätzliche Angaben / Freitext
                  {deactivateReason === "Anderer Grund (siehe unten)" && <span style={{ color: "#A32D2D" }}> *</span>}
                </label>
                <textarea value={deactivateCustom} onChange={e => setDeactivateCustom(e.target.value)}
                  placeholder="Optionale Zusatzinformation für den Kunden..."
                  rows={3}
                  style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, resize: "none", outline: "none" }} />
              </div>
              <div style={{ background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#5F5E5A", marginBottom: 20 }}>
                <div style={{ fontWeight: 500, marginBottom: 4, color: "#1a1a18" }}>E-Mail Vorschau:</div>
                <div><span style={{ color: "#888780" }}>An:</span> {deactivateTarget.admin}</div>
                <div><span style={{ color: "#888780" }}>BCC:</span> superadmin@divelogix360.ch</div>
                <div><span style={{ color: "#888780" }}>Betreff:</span> Ihr DiveLogix360-Zugang wurde deaktiviert</div>
                <div style={{ marginTop: 6, borderTop: "1px solid #D3D1C7", paddingTop: 6 }}>
                  Grund: <em>{deactivateReason || "—"}</em>
                  {deactivateCustom && <div style={{ marginTop: 2 }}>Zusatz: <em>{deactivateCustom}</em></div>}
                </div>
              </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={() => { alert(`Tenant "${deactivateTarget.name}" deaktiviert.\nGrund: ${deactivateReason}\nE-Mail gesendet an ${deactivateTarget.admin}`); closeDialog(); }}
                  disabled={!canSubmit}
                  style={{ padding: "8px 16px", fontSize: 12, background: canSubmit ? "#A32D2D" : "#D3D1C7", border: "none", borderRadius: 6, color: "#fff", cursor: canSubmit ? "pointer" : "not-allowed", fontWeight: 500 }}>
                  Jetzt deaktivieren & E-Mail senden
                </button>
              </div>
            </div>
          </div>
        )}

        {/* TITEL + BUTTON */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Tenants</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>SA-01</span>
            <span style={{ background: "#D3D1C7", color: "#5F5E5A", fontSize: 11, padding: "2px 8px", borderRadius: 20 }}>{TENANTS.length} total</span>
          </div>
          <button onClick={() => alert("→ SA-02: Neuer Tenant")}
            style={{ padding: "8px 16px", fontSize: 13, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 500 }}>
            + Neuer Tenant
          </button>
        </div>

        {/* STATISTIK-KARTEN */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 20 }}>
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "10px 14px" }}>
            <div style={{ fontSize: 10, fontWeight: 500, color: "#888780", marginBottom: 8, textTransform: "uppercase", letterSpacing: 0.5 }}>Nach Status</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
              {[
                { label: "Aktiv",       value: TENANTS.filter(t => t.status === "aktiv").length,           bg: "#EAF3DE", color: "#3B6D11" },
                { label: "Test",        value: TENANTS.filter(t => t.status === "test").length,            bg: "#FAEEDA", color: "#BA7517" },
                { label: "Test abgel.", value: TENANTS.filter(t => t.status === "test-abgelaufen").length, bg: "#FCEBEB", color: "#A32D2D" },
                { label: "Inaktiv",     value: TENANTS.filter(t => t.status === "inaktiv").length,         bg: "#F1EFE8", color: "#5F5E5A" },
              ].map(s => (
                <div key={s.label} style={{ background: s.bg, borderRadius: 6, padding: "8px 10px", textAlign: "center" }}>
                  <div style={{ fontSize: 18, fontWeight: 500, color: s.color }}>{s.value}</div>
                  <div style={{ fontSize: 10, color: s.color, marginTop: 1 }}>{s.label}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "10px 14px" }}>
            <div style={{ fontSize: 10, fontWeight: 500, color: "#888780", marginBottom: 8, textTransform: "uppercase", letterSpacing: 0.5 }}>Nach Plan</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
              {[
                { label: "Test",         value: TENANTS.filter(t => t.plan === "Test").length,         bg: "#F1EFE8", color: "#5F5E5A" },
                { label: "Starter",      value: TENANTS.filter(t => t.plan === "Starter").length,      bg: "#E6F1FB", color: "#185FA5" },
                { label: "Professional", value: TENANTS.filter(t => t.plan === "Professional").length, bg: "#EEEDFE", color: "#534AB7" },
                { label: "Enterprise",   value: TENANTS.filter(t => t.plan === "Enterprise").length,   bg: "#EAF3DE", color: "#3B6D11" },
              ].map(s => (
                <div key={s.label} style={{ background: s.bg, borderRadius: 6, padding: "8px 10px", textAlign: "center" }}>
                  <div style={{ fontSize: 18, fontWeight: 500, color: s.color }}>{s.value}</div>
                  <div style={{ fontSize: 10, color: s.color, marginTop: 1 }}>{s.label}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* FILTER */}
        <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Suche: Name, E-Mail, Slug..."
            style={{ flex: 1, padding: "7px 12px", fontSize: 13, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff", outline: "none" }} />
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
            style={{ padding: "7px 12px", fontSize: 13, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff", outline: "none" }}>
            <option value="alle">Alle Status</option>
            <option value="aktiv">Aktiv</option>
            <option value="test">Test</option>
            <option value="test-abgelaufen">Test abgelaufen</option>
            <option value="inaktiv">Inaktiv</option>
          </select>
          <select value={filterPlan} onChange={e => setFilterPlan(e.target.value)}
            style={{ padding: "7px 12px", fontSize: 13, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff", outline: "none" }}>
            <option value="alle">Alle Pläne</option>
            <option value="Test">Test</option>
            <option value="Starter">Starter</option>
            <option value="Professional">Professional</option>
            <option value="Enterprise">Enterprise</option>
          </select>
        </div>

        {/* TABELLE */}
        <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "2fr 0.7fr 1fr 2fr 1.2fr 1.5fr", padding: "10px 16px", background: "#F1EFE8", borderBottom: "1px solid #D3D1C7" }}>
            {["Schulname / Slug", "Land", "Plan", "Tenant-Admin", "Status", "Aktionen"].map(h => (
              <div key={h} style={{ fontSize: 11, fontWeight: 500, color: "#5F5E5A" }}>{h}</div>
            ))}
          </div>

          {filtered.length === 0 && (
            <div style={{ padding: "24px", textAlign: "center", color: "#888780", fontSize: 13 }}>Keine Tenants gefunden.</div>
          )}

          {filtered.map((t, i) => {
            const st = STATUS_STYLES[t.status];
            const pc = PLAN_COLORS[t.plan];
            const isSelected = selectedSlug === t.slug;
            return (
              <div key={t.slug}
                onClick={() => setSelectedSlug(isSelected ? null : t.slug)}
                style={{
                  display: "grid", gridTemplateColumns: "2fr 0.7fr 1fr 2fr 1.2fr 1.5fr",
                  padding: "12px 16px",
                  borderBottom: i < filtered.length - 1 ? "1px solid #F1EFE8" : "none",
                  background: isSelected ? "#E6F1FB" : "#fff",
                  cursor: "pointer", alignItems: "center"
                }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "#1a1a18" }}>{t.name}</div>
                  <div style={{ fontSize: 11, color: "#888780", fontFamily: "monospace", marginTop: 2 }}>{t.slug}</div>
                  {t.trial && <div style={{ fontSize: 10, color: "#A32D2D", marginTop: 2 }}>Trial bis: {t.trial}</div>}
                </div>
                <div style={{ fontSize: 13, color: "#1a1a18" }}>{t.country}</div>
                <div>
                  <span style={{ background: pc.bg, color: pc.color, fontSize: 11, padding: "2px 8px", borderRadius: 20 }}>{t.plan}</span>
                </div>
                <div style={{ fontSize: 12, color: "#5F5E5A" }}>{t.admin}</div>
                <div>
                  <span style={{ background: st.bg, color: st.color, fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>{st.label}</span>
                </div>
                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                  <button onClick={e => { e.stopPropagation(); alert(`→ SA-03: Detail ${t.name}`); }}
                    style={{ fontSize: 11, padding: "3px 8px", background: "transparent", border: "1px solid #B4B2A9", borderRadius: 4, cursor: "pointer", color: "#5F5E5A" }}>
                    Detail
                  </button>
                  {t.status === "aktiv" && (
                    <button onClick={e => { e.stopPropagation(); setDeactivateTarget(t); }}
                      style={{ fontSize: 11, padding: "3px 8px", background: "#FCEBEB", border: "1px solid #A32D2D", borderRadius: 4, cursor: "pointer", color: "#A32D2D" }}>
                      Deaktivieren
                    </button>
                  )}
                  {(t.status === "inaktiv" || t.status === "test" || t.status === "test-abgelaufen") && (
                    <button onClick={e => { e.stopPropagation(); alert(`Tenant ${t.name} aktivieren?`); }}
                      style={{ fontSize: 11, padding: "3px 8px", background: "#EAF3DE", border: "1px solid #3B6D11", borderRadius: 4, cursor: "pointer", color: "#3B6D11" }}>
                      Aktivieren
                    </button>
                  )}
                  <button onClick={e => { e.stopPropagation(); alert(`→ SA-03: Plan ändern für ${t.name}`); }}
                    style={{ fontSize: 11, padding: "3px 8px", background: "#F1EFE8", border: "1px solid #B4B2A9", borderRadius: 4, cursor: "pointer", color: "#5F5E5A" }}>
                    Plan ändern
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        {/* FUSSZEILE */}
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontSize: 11, color: "#888780" }}>
          <span>{filtered.length} von {TENANTS.length} Tenants angezeigt</span>
          <span>Seite 1 von 1</span>
        </div>

        {/* SIMULATIONSHINWEIS */}
        <div style={{ marginTop: 16, padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Zeile anklicken = markieren. "Detail" → SA-03. "Deaktivieren" → Dialog mit Grund + E-Mail-Vorschau. Filter und Suche sind funktional.
        </div>
      </div>
    </div>
  );
}
