import { useMemo, useState } from "react";

const equipmentTypes = [
  ["cylinder", "Tauchflasche"],
  ["regulator", "Atemregler"],
  ["bcd", "Jacket / BCD"],
  ["computer", "Tauchcomputer"],
  ["suit", "Tauchanzug"],
  ["mask", "Maske"],
  ["fins", "Flossen"],
  ["compass", "Kompass"],
  ["lamp", "Lampe"],
  ["weight", "Blei / Bleisystem"],
  ["smb", "Boje / SMB"],
  ["other", "Sonstiges"],
  ["unknown", "Unbestimmt"],
];

const typeHints = {
  cylinder: "Tauchflasche: Material, Volumen, Arbeitsdruck, Gewinde, Ventiltyp, letzte und nächste Prüfung",
  regulator: "Atemregler: Anschluss, Stufen, letzte und nächste Revision, Serviceintervall",
  other: "Sonstiges: freie Typbezeichnung bleibt sichtbar und kann später katalogisiert werden",
  unknown: "Unbestimmt: temporäre Inventur-ID, nicht workflow-fähig bis Typ qualifiziert ist",
};

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,
};

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

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

export default function EQ04EquipmentBearbeiten() {
  const [equipmentType, setEquipmentType] = useState("cylinder");
  const [originalType] = useState("cylinder");
  const [assignment, setAssignment] = useState("internal");
  const [displayName, setDisplayName] = useState("12l Stahlflasche gelb");
  const [manufacturer, setManufacturer] = useState("Luxfer");
  const [model, setModel] = useState("12l Stahl");
  const [serial, setSerial] = useState("123456");
  const [inventory, setInventory] = useState("INT-0047");
  const [typeLabel, setTypeLabel] = useState("");
  const [customer, setCustomer] = useState("Max Muster");
  const [location, setLocation] = useState("Lager A / Regal 2");
  const [condition, setCondition] = useState("gut");
  const [completionNotes, setCompletionNotes] = useState("Nächste Prüfung und Normreferenz ergänzen.");
  const [changeNote, setChangeNote] = useState("");
  const [offline, setOffline] = useState(false);
  const [message, setMessage] = useState("");

  const quality = useMemo(() => {
    if (equipmentType === "unknown") return "incomplete";
    if (!displayName.trim()) return "incomplete";
    if (assignment === "customer" && !customer.trim()) return "incomplete";
    if (equipmentType === "other" && !typeLabel.trim()) return "incomplete";
    if (!serial.trim() && !inventory.trim()) return "incomplete";
    if (completionNotes.trim()) return "needs_review";
    return "complete";
  }, [equipmentType, displayName, assignment, customer, typeLabel, serial, inventory, completionNotes]);

  const typeChanged = equipmentType !== originalType;
  const criticalChange = typeChanged || !serial.trim() || assignment !== "internal" || quality !== "complete";
  const workflowEligible = quality === "complete" && equipmentType !== "unknown";
  const syncStatus = offline ? "pending_sync" : "synced";

  function save(mode) {
    if (criticalChange && !changeNote.trim()) {
      setMessage("Änderungsnotiz empfohlen oder erforderlich: Typ, Seriennummer, Zuordnung oder Datenqualität wurde kritisch geändert.");
      return;
    }
    setMessage(`${mode}: gespeichert. Datenqualität ${quality}, workflow-fähig ${workflowEligible ? "Ja" : "Nein"}, sync_status ${syncStatus}. Änderung wird auditierbar protokolliert.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 940, 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 · MA</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>Bearbeiten</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 500, color: "#1a1a18" }}>Equipment bearbeiten</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>EQ-04</span>
            <Pill bg={quality === "complete" ? "#EAF3DE" : quality === "needs_review" ? "#FCEBEB" : "#FAEEDA"} color={quality === "complete" ? "#3B6D11" : quality === "needs_review" ? "#A32D2D" : "#BA7517"}>{quality}</Pill>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Änderungen verworfen. Zurück zu EQ-03.")} style={secondaryButton}>Abbrechen</button>
            <button onClick={() => save("Speichern und zurück")} style={outlineButton}>Speichern & zurück</button>
            <button onClick={() => save("Speichern")} style={primaryButton}>Speichern</button>
          </div>
        </div>

        <div style={{ background: criticalChange ? "#FAEEDA" : "#E6F1FB", border: criticalChange ? "1px solid #FAC775" : "1px solid #B5D4F4", borderRadius: 8, padding: "10px 14px", color: criticalChange ? "#BA7517" : "#185FA5", fontSize: 12, marginBottom: 14 }}>
          {criticalChange ? "Kritische Änderung erkannt. Eine Änderungsnotiz sollte erfasst werden." : "Keine kritischen Änderungen erkannt."} Unvollständige Datensätze bleiben für spezifische Workflows gesperrt.
        </div>

        <Section number="1" title="Equipment-Typ" note={typeChanged ? "Typ geändert" : "Originaltyp"}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <label style={labelStyle}>Equipment-Typ *</label>
              <select value={equipmentType} onChange={(e) => setEquipmentType(e.target.value)} style={fieldStyle}>
                {equipmentTypes.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Freie Typbezeichnung</label>
              <input value={typeLabel} onChange={(e) => setTypeLabel(e.target.value)} placeholder="Nur bei other / unknown" disabled={!['other','unknown'].includes(equipmentType)} style={{ ...fieldStyle, background: ['other','unknown'].includes(equipmentType) ? "#fff" : "#F1EFE8" }} />
            </div>
          </div>
          <div style={{ marginTop: 10, background: typeChanged ? "#FAEEDA" : "#E6F1FB", color: typeChanged ? "#BA7517" : "#185FA5", borderRadius: 6, padding: "8px 10px", fontSize: 11 }}>
            {typeHints[equipmentType] || "Typabhängige Zusatzdaten werden passend zum Equipment-Typ angezeigt."}
          </div>
        </Section>

        <Section number="2" title="Basisdaten">
          <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 12, marginBottom: 12 }}>
            <div><label style={labelStyle}>Anzeigename *</label><input value={displayName} onChange={(e) => setDisplayName(e.target.value)} style={fieldStyle} /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div><label style={labelStyle}>Hersteller</label><input value={manufacturer} onChange={(e) => setManufacturer(e.target.value)} style={fieldStyle} /></div>
            <div><label style={labelStyle}>Modell</label><input value={model} onChange={(e) => setModel(e.target.value)} style={fieldStyle} /></div>
            <div><label style={labelStyle}>Seriennummer</label><input value={serial} onChange={(e) => setSerial(e.target.value)} style={fieldStyle} /></div>
            <div><label style={labelStyle}>Inventarnummer</label><input value={inventory} onChange={(e) => setInventory(e.target.value)} style={fieldStyle} /></div>
          </div>
        </Section>

        <Section number="3" title="Zuordnung">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, marginBottom: assignment === "customer" ? 12 : 0 }}>
            {[
              ["internal", "Intern", "Tenant / Tauchschule"],
              ["customer", "Kunde", "Kundenequipment"],
              ["unassigned", "Unbestimmt", "Zuordnung später klären"],
            ].map(([value, title, hint]) => (
              <button key={value} onClick={() => setAssignment(value)} style={{ padding: "12px", borderRadius: 8, border: assignment === value ? "1.5px solid #185FA5" : "1px solid #D3D1C7", background: assignment === value ? "#E6F1FB" : "#fff", color: assignment === value ? "#185FA5" : "#5F5E5A", cursor: "pointer", textAlign: "left" }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
                <div style={{ fontSize: 10, marginTop: 4 }}>{hint}</div>
              </button>
            ))}
          </div>
          {assignment === "customer" && <div><label style={labelStyle}>Kunde suchen *</label><input value="Max Muster" readOnly style={fieldStyle} /></div>}
        </Section>

        <Section number="4" title="Standort & Zustand">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div><label style={labelStyle}>Standort / Lagerort</label><input value={location} onChange={(e) => setLocation(e.target.value)} style={fieldStyle} /></div>
            <div><label style={labelStyle}>Zustand</label><select value={condition} onChange={(e) => setCondition(e.target.value)} style={fieldStyle}><option>neu</option><option>gut</option><option>gebraucht</option><option>beschädigt</option><option>prüfen</option></select></div>
          </div>
        </Section>

        <Section number="5" title="Typabhängige Zusatzdaten" note="Dynamischer Bereich">
          <div style={{ background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 8, padding: "12px 14px", fontSize: 12, color: "#5F5E5A" }}>
            {typeHints[equipmentType] || "Zusatzdaten passend zum gewählten Equipment-Typ."}
            {typeChanged && <div style={{ marginTop: 8, color: "#BA7517" }}>Warnung: Bei Typwechsel können bestehende Detaildaten fachlich nicht mehr passen.</div>}
          </div>
        </Section>

        <Section number="6" title="Datenqualität & Änderungsnotiz">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
            <Pill bg={quality === "complete" ? "#EAF3DE" : quality === "needs_review" ? "#FCEBEB" : "#FAEEDA"} color={quality === "complete" ? "#3B6D11" : quality === "needs_review" ? "#A32D2D" : "#BA7517"}>data_quality_status: {quality}</Pill>
            <Pill bg={workflowEligible ? "#EAF3DE" : "#FCEBEB"} color={workflowEligible ? "#3B6D11" : "#A32D2D"}>Workflow-fähig: {workflowEligible ? "Ja" : "Nein"}</Pill>
            <Pill bg={offline ? "#FAEEDA" : "#EAF3DE"} color={offline ? "#BA7517" : "#3B6D11"}>sync_status: {syncStatus}</Pill>
            <Pill bg="#E6F1FB" color="#185FA5">QR bleibt gültig</Pill>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 12 }}>
            <div><label style={labelStyle}>completion_notes</label><textarea value={completionNotes} onChange={(e) => setCompletionNotes(e.target.value)} rows={3} style={{ ...fieldStyle, resize: "vertical" }} /></div>
            <div><label style={labelStyle}>Änderungsnotiz</label><textarea value={changeNote} onChange={(e) => setChangeNote(e.target.value)} rows={3} placeholder="Warum wurde die Änderung vorgenommen?" style={{ ...fieldStyle, resize: "vertical" }} /></div>
          </div>
          <label style={{ fontSize: 12, color: "#5F5E5A", display: "flex", alignItems: "center", gap: 8 }}><input type="checkbox" checked={offline} onChange={(e) => setOffline(e.target.checked)} /> Offline-Bearbeitung simulieren</label>
        </Section>

        {message && <div style={{ padding: "10px 14px", background: message.includes("Änderungsnotiz") ? "#FAEEDA" : "#EAF3DE", border: message.includes("Änderungsnotiz") ? "1px solid #FAC775" : "1px solid #A8D08D", borderRadius: 8, fontSize: 11, color: message.includes("Änderungsnotiz") ? "#BA7517" : "#3B6D11", 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> Typwechsel, Seriennummer, Zuordnung, completion_notes und Offline-Schalter beeinflussen Datenqualität, Workflow-Fähigkeit und Änderungsnotiz.
        </div>
      </div>
    </div>
  );
}

const primaryButton = { padding: "8px 14px", fontSize: 12, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
const outlineButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #185FA5", borderRadius: 6, color: "#185FA5", cursor: "pointer", fontWeight: 600 };
const secondaryButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
