import { useMemo, useState } from "react";

const EQUIPMENT_TYPES = [
  ["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 TYPE_HINTS = {
  cylinder: "Material, Volumen, Arbeitsdruck, Gewinde, Ventiltyp, letzte und nächste Prüfung",
  regulator: "Anschluss, Stufen, letzte und nächste Revision, Serviceintervall",
  bcd: "Grösse, Bauart, Auftriebsklasse, Sichtprüfung, Inflator-Service",
  computer: "Batterietyp, Luftintegration, Sender, Firmware-Version",
  suit: "Typ, Grösse, Dicke, Schnitt oder Passform",
  mask: "Optische Gläser, Dioptrien, Passform, Farbe",
  fins: "Grösse, Typ, Farbe oder Kennzeichnung",
  compass: "Bauform, Zustand",
  lamp: "Akkutyp, Ladegerät, Lumen, letzte Ladeprüfung",
  weight: "Gewicht, Typ, Kennzeichnung",
  smb: "Grösse, Farbe, Ventiltyp, Zustand",
  other: "Freie Typbezeichnung und flexible Zusatzdaten über custom_data",
  unknown: "Temporäre Inventur-ID; nicht workflow-fähig bis Typ geklärt 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 }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px", marginBottom: 14 }}>
      <div style={{ fontSize: 10, fontWeight: 600, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>
        {number} · {title}
      </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 EQ02NeuesEquipmentErfassen() {
  const [equipmentType, setEquipmentType] = 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 [note, setNote] = useState("Ersterfassungsnotiz: Etikett gut lesbar.");
  const [offline, setOffline] = useState(false);
  const [photoAdded, setPhotoAdded] = useState(false);
  const [completionNotes, setCompletionNotes] = useState("");
  const [lastSave, setLastSave] = 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";
    return "complete";
  }, [equipmentType, displayName, assignment, customer, typeLabel, serial, inventory]);

  const workflowEligible = quality === "complete" && equipmentType !== "unknown";
  const syncStatus = offline ? "local_only" : "synced";

  function save(mode) {
    setLastSave(`${mode}: Datenqualität ${quality}, workflow-fähig ${workflowEligible ? "Ja" : "Nein"}, sync_status ${syncStatus}. QR-Code wird nach Speicherung erzeugt.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 900, 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>Neues Equipment</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" }}>Neues Equipment erfassen</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>EQ-02</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setLastSave("Zurück zu EQ-01")} style={secondaryButton}>Abbrechen</button>
            <button onClick={() => save("Speichern und weiter erfassen")} style={outlineButton}>+ Weiter</button>
            <button onClick={() => save("Speichern")} style={primaryButton}>Speichern</button>
          </div>
        </div>

        <div style={{ background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 8, padding: "10px 14px", color: "#185FA5", fontSize: 12, marginBottom: 14 }}>
          Equipment kann auch unvollständig gespeichert werden. Spezifische Workflows sind erst bei vollständigen Daten möglich.
        </div>

        <Section number="1" title="Equipment-Typ">
          <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}>
                {EQUIPMENT_TYPES.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 Sonstiges oder unknown" disabled={!['other','unknown'].includes(equipmentType)} style={{ ...fieldStyle, background: ['other','unknown'].includes(equipmentType) ? "#fff" : "#F1EFE8" }} />
            </div>
          </div>
          <div style={{ marginTop: 10, background: equipmentType === "unknown" ? "#FCEBEB" : "#FAEEDA", color: equipmentType === "unknown" ? "#A32D2D" : "#BA7517", borderRadius: 6, padding: "8px 10px", fontSize: 11 }}>
            {TYPE_HINTS[equipmentType]}
          </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>
          <p style={{ fontSize: 11, color: "#888780", margin: "10px 0 0" }}>Mindestens Seriennummer oder Inventarnummer bei qualifizierter Erfassung.</p>
        </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={customer} onChange={(e) => setCustomer(e.target.value)} style={fieldStyle} /></div>}
        </Section>

        <Section number="4" title="Standort, Zustand, Foto, Notiz">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 12 }}>
            <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>
          <div style={{ display: "grid", gridTemplateColumns: "170px 1fr", gap: 14 }}>
            <button onClick={() => setPhotoAdded(!photoAdded)} style={{ border: "1px dashed #B4B2A9", borderRadius: 8, background: photoAdded ? "#EAF3DE" : "#F1EFE8", color: photoAdded ? "#3B6D11" : "#5F5E5A", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>{photoAdded ? "Foto hinzugefügt" : "+ Hauptfoto"}</button>
            <div><label style={labelStyle}>Erstnotiz</label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} style={{ ...fieldStyle, resize: "vertical" }} /></div>
          </div>
        </Section>

        <Section number="5" title="Typabhängige Zusatzdaten">
          <div style={{ background: "#F1EFE8", border: "1px solid #D3D1C7", borderRadius: 8, padding: "12px 14px", fontSize: 12, color: "#5F5E5A" }}>
            <strong>{EQUIPMENT_TYPES.find(([value]) => value === equipmentType)?.[1]}:</strong> {TYPE_HINTS[equipmentType]}
            <div style={{ marginTop: 8, fontSize: 11, color: "#888780" }}>Dieser Bereich ist im echten UI dynamisch und hängt vom Equipment-Typ ab.</div>
          </div>
        </Section>

        <Section number="6" title="Datenqualität / Workflow-Fähigkeit">
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 12 }}>
            <Pill bg={quality === "complete" ? "#EAF3DE" : "#FAEEDA"} color={quality === "complete" ? "#3B6D11" : "#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-Code nach Speicherung</Pill>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 14, alignItems: "start" }}>
            <div><label style={labelStyle}>completion_notes</label><textarea value={completionNotes} onChange={(e) => setCompletionNotes(e.target.value)} rows={2} placeholder="Welche Angaben müssen später ergänzt oder geprüft werden?" style={{ ...fieldStyle, resize: "vertical" }} /></div>
            <label style={{ fontSize: 12, color: "#5F5E5A", display: "flex", alignItems: "center", gap: 8, marginTop: 26 }}><input type="checkbox" checked={offline} onChange={(e) => setOffline(e.target.checked)} /> Offline simulieren</label>
          </div>
        </Section>

        {lastSave && <div style={{ padding: "10px 14px", background: "#EAF3DE", border: "1px solid #A8D08D", borderRadius: 8, fontSize: 11, color: "#3B6D11", marginBottom: 12 }}>{lastSave}</div>}

        <div style={{ padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Typ, Zuordnung, Pflichtfelder und Offline-Schalter beeinflussen Datenqualität, Workflow-Fähigkeit und Sync-Status.
        </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" };
