import { useState } from "react";

const PLANS = ["Test", "Starter", "Professional", "Enterprise"];
const COUNTRIES = ["CH – Schweiz", "DE – Deutschland", "AT – Österreich"];
const CURRENCIES = ["CHF – Schweizer Franken", "EUR – Euro"];

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

const TEST_DEFAULTS = { days: "30", maxUsers: "1", maxCustomers: "2", maxCylinders: "5" };

function Field({ label, required, hint, error, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18", marginBottom: 5 }}>
        {label}{required && <span style={{ color: "#A32D2D", marginLeft: 2 }}>*</span>}
      </label>
      {children}
      {hint && !error && <div style={{ fontSize: 10, color: "#888780", marginTop: 4 }}>{hint}</div>}
      {error && <div style={{ fontSize: 10, color: "#A32D2D", marginTop: 4 }}>⚠ {error}</div>}
    </div>
  );
}

const inputStyle = (hasError) => ({
  width: "100%", boxSizing: "border-box",
  padding: "8px 12px", fontSize: 12,
  border: `1px solid ${hasError ? "#A32D2D" : "#B4B2A9"}`,
  borderRadius: 6, background: "#fff", outline: "none",
});

const selectStyle = {
  width: "100%", boxSizing: "border-box",
  padding: "8px 12px", fontSize: 12,
  border: "1px solid #B4B2A9",
  borderRadius: 6, background: "#fff", outline: "none",
};

export default function SA02() {
  const [form, setForm] = useState({
    name: "", country: "", plan: "", email: "",
    street: "", zip: "", city: "", currency: "",
    testDays: TEST_DEFAULTS.days,
    testMaxUsers: TEST_DEFAULTS.maxUsers,
    testMaxCustomers: TEST_DEFAULTS.maxCustomers,
    testMaxCylinders: TEST_DEFAULTS.maxCylinders,
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const set = (key) => (e) => setForm(f => ({ ...f, [key]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!form.name.trim())    e.name    = "Schulname ist ein Pflichtfeld";
    if (!form.country)        e.country = "Land ist ein Pflichtfeld";
    if (!form.plan)           e.plan    = "Plan-Typ ist ein Pflichtfeld";
    if (!form.email.trim())   e.email   = "E-Mail ist ein Pflichtfeld";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
                              e.email   = "Ungültige E-Mail-Adresse";
    return e;
  };

  const handleSubmit = () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) setSubmitted(true);
  };

  const handleReset = () => {
    setForm({ name: "", country: "", plan: "", email: "", street: "", zip: "", city: "", currency: "",
      testDays: TEST_DEFAULTS.days, testMaxUsers: TEST_DEFAULTS.maxUsers,
      testMaxCustomers: TEST_DEFAULTS.maxCustomers, testMaxCylinders: TEST_DEFAULTS.maxCylinders });
    setErrors({});
    setSubmitted(false);
  };

  const slug = form.name ? "wird generiert…" : "—";

  // ── BESTÄTIGUNGS-SCREEN ──
  if (submitted) {
    return (
      <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 500, borderRadius: 8, overflow: "hidden" }}>
        <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: "40px 24px", display: "flex", flexDirection: "column", alignItems: "center", gap: 16 }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#EAF3DE", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 28 }}>✓</div>
          <div style={{ fontSize: 18, fontWeight: 500, color: "#1a1a18" }}>Tenant angelegt & Einladung gesendet</div>
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 24px", width: "100%", maxWidth: 480 }}>
            <div style={{ fontSize: 11, fontWeight: 500, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>Zusammenfassung</div>
            {[
              ["Schulname", form.name],
              ["Land", form.country],
              ["Plan", form.plan],
              ["Einladung gesendet an", form.email],
              ["Token-Ablauf", "72 Stunden ab jetzt"],
            ].map(([label, value]) => (
              <div key={label} style={{ display: "flex", fontSize: 12, marginBottom: 8, paddingBottom: 8, borderBottom: "1px solid #F1EFE8" }}>
                <span style={{ color: "#888780", minWidth: 160 }}>{label}</span>
                <span style={{ color: "#1a1a18" }}>{value}</span>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={handleReset}
              style={{ padding: "8px 20px", fontSize: 12, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 500 }}>
              Weiteren Tenant anlegen
            </button>
            <button onClick={() => alert("→ SA-01: Zurück zur Tenant-Liste")}
              style={{ padding: "8px 20px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>
              Zur Tenant-Liste
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── HAUPT-FORMULAR ──
  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" }} onClick={() => alert("→ SA-01: Tenant-Liste")}>Tenants</span>
          <span style={{ margin: "0 6px" }}>›</span>
          <span>Neuer Tenant</span>
        </div>

        {/* TITEL */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
          <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Neuer Tenant anlegen</h1>
          <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>SA-02</span>
        </div>

        {/* INFO-BANNER */}
        <div style={{ background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#185FA5", marginBottom: 20 }}>
          ℹ Nach dem Anlegen erhält der Schulinhaber automatisch eine Einladungs-E-Mail mit einem 72-Stunden-Link.
        </div>

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

          {/* ── PFLICHTANGABEN ── */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Pflichtangaben</span>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
          </div>

          <Field label="Schulname" required error={errors.name}
            hint="Vollständiger offizieller Name der Tauchschule">
            <input value={form.name} onChange={set("name")} placeholder="z.B. Tauchschule Zürich GmbH"
              style={inputStyle(errors.name)} />
          </Field>

          <Field label="Land" required error={errors.country}
            hint="Bestimmt die gültigen Compliance-Regeln (DSGVO / nDSG / DSG)">
            <select value={form.country} onChange={set("country")} style={selectStyle}>
              <option value="">— bitte wählen —</option>
              {COUNTRIES.map(c => <option key={c}>{c}</option>)}
            </select>
          </Field>

          <Field label="Plan-Typ" required error={errors.plan}
            hint="Limits werden aus plan_features geladen – Superadmin kann pro Tenant überschreiben">
            <select value={form.plan} onChange={set("plan")} style={selectStyle}>
              <option value="">— bitte wählen —</option>
              {PLANS.map(p => <option key={p}>{p}</option>)}
            </select>
            {form.plan && (
              <div style={{ marginTop: 6 }}>
                <span style={{ background: PLAN_COLORS[form.plan]?.bg, color: PLAN_COLORS[form.plan]?.color, fontSize: 11, padding: "2px 10px", borderRadius: 20 }}>{form.plan}</span>
              </div>
            )}
          </Field>

          {/* TEST-PARAMETER BOX */}
          {form.plan === "Test" && (
            <div style={{ background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 6, padding: "14px 16px", marginBottom: 18 }}>
              <div style={{ fontSize: 11, fontWeight: 500, color: "#BA7517", marginBottom: 10 }}>
                Test-Parameter
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 8 }}>
                {[
                  { label: "Gültig (Tage)", key: "testDays" },
                  { label: "Max. Users", key: "testMaxUsers" },
                  { label: "Max. Kunden", key: "testMaxCustomers" },
                  { label: "Max. Flaschen", key: "testMaxCylinders" },
                ].map(({ label, key }) => (
                  <div key={key}>
                    <div style={{ fontSize: 10, color: "#BA7517", marginBottom: 4 }}>{label}</div>
                    <input value={form[key]} onChange={set(key)} type="number" min="1"
                      style={{ width: "100%", boxSizing: "border-box", padding: "5px 8px", fontSize: 12, border: "1px solid #FAC775", borderRadius: 4, background: "#fff", outline: "none" }} />
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 10, color: "#BA7517", marginTop: 10 }}>
                ⚠ Erinnerungs-E-Mail wird automatisch ab Tag 20 gesendet
              </div>
            </div>
          )}

          <Field label="E-Mail Schulinhaber (Tenant-Admin)" required error={errors.email}
            hint="Wird als Login-E-Mail und für die Einladung verwendet">
            <input value={form.email} onChange={set("email")} placeholder="inhaber@tauchschule.ch"
              type="email" style={inputStyle(errors.email)} />
          </Field>

          {/* ── OPTIONALE ANGABEN ── */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20, marginTop: 8 }}>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Optionale Angaben (kann Schulinhaber später ergänzen)</span>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Strasse / Nr.">
              <input value={form.street} onChange={set("street")} placeholder="Seestrasse 12" style={inputStyle()} />
            </Field>
            <Field label="PLZ">
              <input value={form.zip} onChange={set("zip")} placeholder="8001" style={inputStyle()} />
            </Field>
            <Field label="Stadt">
              <input value={form.city} onChange={set("city")} placeholder="Zürich" style={inputStyle()} />
            </Field>
            <Field label="Standard-Währung" hint="Standard: CHF">
              <select value={form.currency} onChange={set("currency")} style={selectStyle}>
                <option value="">— bitte wählen —</option>
                {CURRENCIES.map(c => <option key={c}>{c}</option>)}
              </select>
            </Field>
          </div>

          {/* ── SYSTEMGENERIERTE WERTE ── */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20, marginTop: 8 }}>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Systemgenerierte Werte (nicht editierbar)</span>
            <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 24 }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 500, color: "#888780", marginBottom: 5 }}>Slug (URL-Kennung)</div>
              <div style={{ padding: "8px 12px", fontSize: 12, background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 6, color: "#888780", fontFamily: "monospace" }}>
                {slug}
              </div>
              <div style={{ fontSize: 10, color: "#888780", marginTop: 4 }}>8-stellig, zufällig, z.B. "k7x2m9pq"</div>
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 500, color: "#888780", marginBottom: 5 }}>Token-Ablauf</div>
              <div style={{ padding: "8px 12px", fontSize: 12, background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 6, color: "#888780" }}>
                72 Stunden ab Versand
              </div>
            </div>
          </div>

          {/* TRENNLINIE + BUTTONS */}
          <div style={{ borderTop: "1px solid #D3D1C7", paddingTop: 20, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <span style={{ fontSize: 11, color: "#888780" }}><span style={{ color: "#A32D2D" }}>*</span> Pflichtfeld</span>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={() => alert("→ SA-01: Abbrechen, zurück zur Tenant-Liste")}
                style={{ padding: "8px 20px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" }}>
                Abbrechen
              </button>
              <button onClick={handleSubmit}
                style={{ padding: "8px 20px", fontSize: 12, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 500 }}>
                Tenant anlegen & Einladung senden →
              </button>
            </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> Pflichtfelder werden validiert. Plan "Test" zeigt Test-Parameter-Box. Formular absenden zeigt Bestätigungs-Screen. Slug wird bei Namenseingabe als "wird generiert…" angezeigt.
        </div>

      </div>
    </div>
  );
}
