import { useMemo, useState } from "react";

const positions = [
  { id: "eq-001", name: "12l Stahlflasche gelb", serial: "123456", due: "2026-04-30", state: "überfällig" },
  { id: "eq-002", name: "10l Aluflasche silber", serial: "AL-9001", due: "2026-05-20", state: "fällig" },
  { id: "eq-004", name: "7l Stage Stahl", serial: "STAGE-07", due: "2026-05-25", state: "fällig" },
];

const resultOptions = {
  passed: { label: "passed", bg: "#EAF3DE", color: "#3B6D11", impact: "Prüfdatum und nächste Prüfung werden aktualisiert. Sperrwirkung kann aufgehoben werden." },
  failed: { label: "failed", bg: "#FCEBEB", color: "#A32D2D", impact: "Equipment wird needs_review und operativ inactive. Weiter zu TÜV-06." },
  rework_required: { label: "rework_required", bg: "#FAEEDA", color: "#BA7517", impact: "Nacharbeit erforderlich. Position bleibt gesperrt. Weiter zu TÜV-06." },
};

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 TUEV05PruefergebnisErfassen() {
  const [selectedIds, setSelectedIds] = useState(["eq-001"]);
  const [result, setResult] = useState("passed");
  const [inspectionDate, setInspectionDate] = useState("2026-05-06");
  const [reference, setReference] = useState("");
  const [suggestedDue] = useState("2028-05-06");
  const [finalDue, setFinalDue] = useState("2028-05-06");
  const [overrideReason, setOverrideReason] = useState("");
  const [remark, setRemark] = useState("Prüfung gemäss externer Rückmeldung erfasst.");
  const [message, setMessage] = useState("");

  const selectedResult = resultOptions[result];
  const manualOverride = result === "passed" && finalDue !== suggestedDue;
  const critical = result === "failed" || result === "rework_required";

  const validation = useMemo(() => {
    const errors = [];
    if (selectedIds.length === 0) errors.push("Mindestens eine Position muss ausgewählt sein.");
    if (!inspectionDate) errors.push("Prüfdatum ist Pflicht.");
    if (result === "passed" && !finalDue) errors.push("Nächste Prüfung ist bei passed Pflicht.");
    if (manualOverride && !overrideReason.trim()) errors.push("Manuelle Übersteuerung benötigt eine Begründung.");
    if (critical && !remark.trim()) errors.push("Bei failed oder rework_required ist eine Bemerkung Pflicht.");
    return errors;
  }, [selectedIds, inspectionDate, result, finalDue, manualOverride, overrideReason, critical, remark]);

  function togglePosition(id) {
    setSelectedIds((current) => current.includes(id) ? current.filter((item) => item !== id) : [...current, id]);
  }

  function save() {
    if (validation.length > 0) {
      setMessage(`Speichern blockiert: ${validation.join(" ")}`);
      return;
    }
    const suffix = critical ? " Folgeaktion TÜV-06 wird angeboten." : " Rückkehr zu TÜV-03.";
    setMessage(`Ergebnis gespeichert: ${result} für ${selectedIds.length} Position(en). Workflow-Historie und Audit-Log wurden fortgeschrieben.${suffix}`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 820, 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: "#888780" }}>Equipment</span>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>TÜV-Inspektion</span>
          <span style={{ color: "#888780" }}>Fristen</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" }}>TÜV-Inspektion</span><span style={{ margin: "0 6px" }}>›</span><span style={{ color: "#185FA5" }}>TÜV Sammelprüfung Mai 2026</span><span style={{ margin: "0 6px" }}>›</span><span>Prüfergebnis erfassen</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" }}>Prüfergebnis erfassen</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>TÜV-05</span>
            <Pill bg={selectedResult.bg} color={selectedResult.color}>{selectedResult.label}</Pill>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zu TÜV-03 ohne Änderung.")} style={secondaryButton}>Abbrechen</button>
            <button onClick={save} style={primaryButton}>Ergebnis speichern</button>
          </div>
        </div>

        <Card title="1 · Prüfauftrag">
          <div style={{ display: "flex", justifyContent: "space-between", gap: 14 }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600, color: "#1a1a18" }}>TÜV Sammelprüfung Mai 2026</div>
              <div style={{ fontSize: 12, color: "#888780", marginTop: 4 }}>Auftrag: TUV-2026-0007 · Prüfstelle: SVTI / Dienstleister Beispiel · Status: in_progress</div>
            </div>
            <Pill bg="#E6F1FB" color="#185FA5">in_progress</Pill>
          </div>
        </Card>

        <Card title="2 · Positionswahl" action={<span style={{ fontSize: 11, color: "#888780" }}>{selectedIds.length} ausgewählt</span>}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            {positions.map((position) => {
              const selected = selectedIds.includes(position.id);
              return (
                <button key={position.id} onClick={() => togglePosition(position.id)} style={{ padding: 12, borderRadius: 8, border: selected ? "1.5px solid #185FA5" : "1px solid #D3D1C7", background: selected ? "#E6F1FB" : "#fff", color: selected ? "#185FA5" : "#1a1a18", cursor: "pointer", textAlign: "left" }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{position.name}</div>
                  <div style={{ fontSize: 10, marginTop: 6 }}>SN {position.serial} · {position.state}</div>
                </button>
              );
            })}
          </div>
        </Card>

        <Card title="3 · Ergebnisdaten">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 8 }}>Prüfergebnis *</div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {Object.entries(resultOptions).map(([value, option]) => (
                  <button key={value} onClick={() => setResult(value)} style={{ padding: "8px 12px", borderRadius: 8, border: result === value ? `1.5px solid ${option.color}` : "1px solid #D3D1C7", background: result === value ? option.bg : "#fff", color: result === value ? option.color : "#5F5E5A", cursor: "pointer", fontWeight: 600 }}>{option.label}</button>
                ))}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <Field label="Prüfdatum *"><input type="date" value={inspectionDate} onChange={(e) => setInspectionDate(e.target.value)} style={fieldStyle} /></Field>
              <Field label="Prüfnummer / Referenz"><input value={reference} onChange={(e) => setReference(e.target.value)} placeholder="optional" style={fieldStyle} /></Field>
            </div>
          </div>
        </Card>

        <Card title="4 · Nächste Prüfung">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            <Field label="Systemvorschlag"><input value={suggestedDue} readOnly style={{ ...fieldStyle, background: "#F1EFE8" }} /></Field>
            <Field label="Final gespeichertes Datum *"><input type="date" value={finalDue} onChange={(e) => setFinalDue(e.target.value)} disabled={result !== "passed"} style={fieldStyle} /></Field>
            <div style={{ display: "flex", alignItems: "end" }}><button onClick={() => setFinalDue(suggestedDue)} disabled={result !== "passed"} style={outlineButton}>Vorschlag übernehmen</button></div>
          </div>
          {manualOverride && <div style={{ marginTop: 12 }}><Field label="Begründung Übersteuerung *"><input value={overrideReason} onChange={(e) => setOverrideReason(e.target.value)} placeholder="z. B. Datum gemäss Prüfbericht übernommen" style={fieldStyle} /></Field></div>}
        </Card>

        <Card title="5 · Bemerkung / Referenz">
          <textarea value={remark} onChange={(e) => setRemark(e.target.value)} rows={3} placeholder="Bemerkung zum Prüfergebnis erfassen..." style={{ ...fieldStyle, resize: "vertical" }} />
          <div style={{ marginTop: 8, fontSize: 11, color: critical ? "#BA7517" : "#888780" }}>{critical ? "Bemerkung ist bei failed oder rework_required Pflicht." : "Bemerkung ist optional, aber empfohlen."}</div>
        </Card>

        <Card title="6 · Auswirkung">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill bg={selectedResult.bg} color={selectedResult.color}>{selectedResult.label}</Pill>
            {manualOverride && <Pill bg="#FAEEDA" color="#BA7517">manuell übersteuert</Pill>}
            {critical && <Pill bg="#FCEBEB" color="#A32D2D">TÜV-06 erforderlich</Pill>}
          </div>
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>{selectedResult.impact}</div>
          {critical && <button onClick={() => setMessage("Öffnet TÜV-06 Nacharbeit / nicht bestanden.")} style={{ ...dangerButton, marginTop: 12 }}>Weiter zu TÜV-06</button>}
        </Card>

        {message && <div style={{ padding: "10px 14px", background: message.includes("blockiert") ? "#FAEEDA" : "#EAF3DE", border: message.includes("blockiert") ? "1px solid #FAC775" : "1px solid #A8D08D", borderRadius: 8, fontSize: 12, color: message.includes("blockiert") ? "#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> Positionsauswahl, Ergebnis, nächste Prüfung und manuelle Übersteuerung beeinflussen Validierung und Folgeaktionen.
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18" }}><span style={{ display: "block", marginBottom: 6 }}>{label}</span>{children}</label>;
}

const fieldStyle = { width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff" };
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" };
const dangerButton = { padding: "8px 14px", fontSize: 12, background: "#A32D2D", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
