import { useMemo, useState } from "react";

const statusOptions = {
  inactive: {
    title: "inactive",
    subtitle: "Vorübergehend nicht in Nutzung",
    detail: "Bleibt sichtbar, aber nicht für normale Workflows nutzbar.",
    bg: "#E6F1FB",
    color: "#185FA5",
  },
  retired: {
    title: "retired",
    subtitle: "Dauerhaft ausgemustert",
    detail: "Nicht mehr nutzbar, bleibt historisch sichtbar.",
    bg: "#FAEEDA",
    color: "#BA7517",
  },
  archived: {
    title: "archived",
    subtitle: "Historisch aufbewahrt",
    detail: "Aus Standardlisten ausgeblendet, nur per Archiv-Filter sichtbar.",
    bg: "#FCEBEB",
    color: "#A32D2D",
  },
};

function Pill({ children, bg, color }) {
  return <span style={{ background: bg, color, borderRadius: 999, padding: "3px 9px", fontSize: 11, fontWeight: 600 }}>{children}</span>;
}

function Card({ title, children, action }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px", marginBottom: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5 }}>{title}</div>
        {action}
      </div>
      {children}
    </div>
  );
}

export default function EQ06EquipmentArchivieren() {
  const [targetStatus, setTargetStatus] = useState("inactive");
  const [hasOpenWorkflow, setHasOpenWorkflow] = useState(true);
  const [hasActiveRental, setHasActiveRental] = useState(false);
  const [hasSyncConflict, setHasSyncConflict] = useState(false);
  const [reason, setReason] = useState("Vorübergehend ausser Betrieb");
  const [note, setNote] = useState("Sichtprüfung offen, Gerät bis zur Klärung nicht im Schulbetrieb verwenden.");
  const [confirmed, setConfirmed] = useState(false);
  const [message, setMessage] = useState("");

  const selected = statusOptions[targetStatus];
  const hardBlock = hasActiveRental || hasSyncConflict;
  const warning = hasOpenWorkflow && !hardBlock;

  const impact = useMemo(() => {
    if (targetStatus === "inactive") return "Bleibt sichtbar, ist aber für normale Workflows gesperrt.";
    if (targetStatus === "retired") return "Wird dauerhaft ausgemustert und ist nicht mehr nutzbar.";
    return "Wird aus Standardlisten ausgeblendet und nur historisch angezeigt.";
  }, [targetStatus]);

  function save() {
    if (hardBlock) {
      setMessage("Statuswechsel blockiert: Aktiver Verleih oder Sync-Konflikt muss zuerst gelöst werden.");
      return;
    }
    if (!reason.trim() || !note.trim()) {
      setMessage("Grund und Pflichtnotiz sind erforderlich.");
      return;
    }
    if (!confirmed) {
      setMessage("Bestätigung fehlt: Bitte Auswirkungen des Statuswechsels bestätigen.");
      return;
    }
    setMessage(`Status geändert zu ${targetStatus}. Equipment ist nicht workflow-fähig. Audit-Log und strukturierte Notiz wurden erstellt.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 760, borderRadius: 8, overflow: "hidden" }}>
      <div style={{ background: "#1a1a18", padding: "10px 20px", fontSize: 13, display: "flex", alignItems: "center", gap: 16 }}>
        <span style={{ fontWeight: 700, color: "#fff" }}>DiveLogix360</span>
        <span style={{ color: "#5F5E5A" }}>|</span>
        <span style={{ color: "#888780" }}>Tenant-Portal</span>
        <div style={{ marginLeft: "auto", display: "flex", gap: 16, fontSize: 12 }}>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>Equipment</span>
          <span style={{ color: "#888780" }}>Kunden</span>
          <span style={{ color: "#888780" }}>Workflows</span>
          <span style={{ color: "#D3D1C7", fontWeight: 500 }}>TSH · Admin</span>
        </div>
      </div>

      <div style={{ padding: "18px 24px" }}>
        <div style={{ fontSize: 12, color: "#888780", marginBottom: 12 }}>
          <span style={{ color: "#185FA5" }}>Equipment</span><span style={{ margin: "0 6px" }}>›</span><span style={{ color: "#185FA5" }}>12l Stahlflasche gelb</span><span style={{ margin: "0 6px" }}>›</span><span>Archivieren</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 500, color: "#1a1a18" }}>Equipment archivieren</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>EQ-06</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zu EQ-03 ohne Änderung.")} style={secondaryButton}>Abbrechen</button>
            <button onClick={save} style={dangerButton}>Status ändern</button>
          </div>
        </div>

        <Card title="Equipment">
          <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: "#1a1a18" }}>12l Stahlflasche gelb</div>
              <div style={{ fontSize: 12, color: "#888780", marginTop: 4 }}>Tauchflasche · SN 123456 · INV INT-0047 · Intern · Lager A</div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", justifyContent: "flex-end" }}>
              <Pill bg="#EAF3DE" color="#3B6D11">active</Pill>
              <Pill bg="#EAF3DE" color="#3B6D11">complete</Pill>
              <Pill bg="#E6F1FB" color="#185FA5">QR bleibt erhalten</Pill>
            </div>
          </div>
        </Card>

        <Card title="1 · Vorprüfung">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            <CheckToggle label="Offene Workflows" checked={hasOpenWorkflow} onChange={setHasOpenWorkflow} warning />
            <CheckToggle label="Aktiver Verleih" checked={hasActiveRental} onChange={setHasActiveRental} danger />
            <CheckToggle label="Sync-Konflikt" checked={hasSyncConflict} onChange={setHasSyncConflict} danger />
          </div>
          <div style={{ marginTop: 12, fontSize: 12, color: hardBlock ? "#A32D2D" : warning ? "#BA7517" : "#3B6D11" }}>
            {hardBlock ? "Blockade: Statuswechsel nicht erlaubt." : warning ? "Warnung: Offene Workflows prüfen." : "Vorprüfung ohne Blockade."}
          </div>
        </Card>

        <Card title="2 · Zielstatus wählen">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            {Object.entries(statusOptions).map(([key, option]) => (
              <button key={key} onClick={() => setTargetStatus(key)} style={{ padding: 14, borderRadius: 8, border: targetStatus === key ? `1.5px solid ${option.color}` : "1px solid #D3D1C7", background: targetStatus === key ? option.bg : "#fff", color: targetStatus === key ? option.color : "#5F5E5A", cursor: "pointer", textAlign: "left", minHeight: 96 }}>
                <div style={{ fontSize: 15, fontWeight: 700 }}>{option.title}</div>
                <div style={{ fontSize: 11, marginTop: 8 }}>{option.subtitle}</div>
                <div style={{ fontSize: 10, marginTop: 8 }}>{option.detail}</div>
              </button>
            ))}
          </div>
        </Card>

        <Card title="3 · Auswirkungen">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill bg={selected.bg} color={selected.color}>Zielstatus: {targetStatus}</Pill>
            <Pill bg="#FCEBEB" color="#A32D2D">Workflow: Nein</Pill>
            <Pill bg="#E6F1FB" color="#185FA5">QR zeigt {targetStatus}</Pill>
            <Pill bg="#EAF3DE" color="#3B6D11">Audit-Log</Pill>
          </div>
          <div style={{ fontSize: 12, color: "#5F5E5A" }}>{impact}</div>
        </Card>

        <Card title="4 · Grund / Pflichtnotiz">
          <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 14 }}>
            <div>
              <label style={labelStyle}>Grund *</label>
              <select value={reason} onChange={(e) => setReason(e.target.value)} style={fieldStyle}>
                <option>Vorübergehend ausser Betrieb</option>
                <option>Dauerhaft ausgemustert</option>
                <option>Historisch archiviert</option>
                <option>Verkauft / abgegeben</option>
                <option>Sonstiger Grund</option>
              </select>
            </div>
            <div>
              <label style={labelStyle}>Notiz *</label>
              <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} style={{ ...fieldStyle, resize: "vertical" }} />
            </div>
          </div>
        </Card>

        <Card title="5 · Bestätigung">
          <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12, color: "#5F5E5A" }}>
            <input type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} />
            <span>Ich bestätige, dass dieser Statuswechsel Auswirkungen auf Sichtbarkeit und Workflow-Nutzung hat.</span>
          </label>
        </Card>

        {message && <div style={{ padding: "10px 14px", background: message.includes("geändert") ? "#EAF3DE" : "#FAEEDA", border: message.includes("geändert") ? "1px solid #A8D08D" : "1px solid #FAC775", borderRadius: 8, fontSize: 12, color: message.includes("geändert") ? "#3B6D11" : "#BA7517", marginBottom: 12 }}>{message}</div>}

        <div style={{ padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Aktiver Verleih und Sync-Konflikt blockieren. Offene Workflows erzeugen Warnung. Grund, Notiz und Bestätigung sind Pflicht.
        </div>
      </div>
    </div>
  );
}

function CheckToggle({ label, checked, onChange, warning, danger }) {
  const color = danger ? "#A32D2D" : warning ? "#BA7517" : "#3B6D11";
  const bg = checked ? (danger ? "#FCEBEB" : warning ? "#FAEEDA" : "#EAF3DE") : "#fff";
  return (
    <button onClick={() => onChange(!checked)} style={{ border: `1px solid ${checked ? color : "#D3D1C7"}`, background: bg, borderRadius: 8, padding: 12, textAlign: "left", cursor: "pointer", color }}>
      <div style={{ fontSize: 13, fontWeight: 700 }}>{checked ? "Aktiv" : "Nicht aktiv"}</div>
      <div style={{ fontSize: 11, marginTop: 4 }}>{label}</div>
    </button>
  );
}

const fieldStyle = { width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff" };
const labelStyle = { display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18", marginBottom: 6 };
const secondaryButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
const dangerButton = { padding: "8px 14px", fontSize: 12, background: "#A32D2D", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
