import { useMemo, useState } from "react";

const categories = ["Korrosion", "Gewinde", "Ventil", "Druckprüfung", "Sichtprüfung", "Dokumentation", "Sonstiges"];
const severities = ["niedrig", "mittel", "hoch", "kritisch"];

const actions = {
  rework: {
    label: "Nacharbeit durchführen",
    bg: "#FAEEDA",
    color: "#BA7517",
    impact: "Equipment bleibt inactive und needs_review. Nacharbeit wird geplant.",
  },
  retest: {
    label: "erneute Prüfung vorbereiten",
    bg: "#E6F1FB",
    color: "#185FA5",
    impact: "Equipment bleibt gesperrt. Folgeauftrag kann über TÜV-02 vorbereitet werden.",
  },
  internal_review: {
    label: "intern prüfen",
    bg: "#EEEDFE",
    color: "#534AB7",
    impact: "Fachliche Klärung durch Tauchschule. Wiedervorlage empfohlen.",
  },
  retire: {
    label: "ausmustern",
    bg: "#FCEBEB",
    color: "#A32D2D",
    impact: "Equipment wird retired und dauerhaft aus dem aktiven Bestand entfernt.",
  },
  open: {
    label: "Entscheidung offen",
    bg: "#F1EFE8",
    color: "#5F5E5A",
    impact: "Equipment bleibt gesperrt, bis die Entscheidung abgeschlossen ist.",
  },
};

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 TUEV06NacharbeitNichtBestanden() {
  const [category, setCategory] = useState("Korrosion");
  const [severity, setSeverity] = useState("hoch");
  const [reworkPossible, setReworkPossible] = useState("unklar");
  const [description, setDescription] = useState("Mangel gemäss Rückmeldung der Prüfstelle dokumentiert.");
  const [nextAction, setNextAction] = useState("rework");
  const [note, setNote] = useState("Equipment bleibt bis zur Klärung gesperrt.");
  const [followUpDate, setFollowUpDate] = useState("");
  const [retireConfirmed, setRetireConfirmed] = useState(false);
  const [message, setMessage] = useState("");

  const action = actions[nextAction];
  const isRetire = nextAction === "retire";

  const validation = useMemo(() => {
    const errors = [];
    if (!category) errors.push("Grundkategorie ist Pflicht.");
    if (!description.trim()) errors.push("Beschreibung ist Pflicht.");
    if (!severity) errors.push("Schweregrad ist Pflicht.");
    if (!nextAction) errors.push("Nächste Massnahme ist Pflicht.");
    if (!note.trim()) errors.push("Pflichtnotiz ist erforderlich.");
    if (isRetire && !retireConfirmed) errors.push("Ausmustern benötigt eine ausdrückliche Bestätigung.");
    return errors;
  }, [category, description, severity, nextAction, note, isRetire, retireConfirmed]);

  function save() {
    if (validation.length > 0) {
      setMessage(`Speichern blockiert: ${validation.join(" ")}`);
      return;
    }

    const status = isRetire ? "retired" : "inactive";
    setMessage(
      `Massnahme gespeichert: ${action.label}. Equipment wird auf needs_review und ${status} gesetzt. Workflow-Historie und Audit-Log wurden fortgeschrieben.`
    );
  }

  function openTarget(target) {
    setMessage(`Öffnet ${target}.`);
  }

  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>Nacharbeit / nicht bestanden</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" }}>Nacharbeit / nicht bestanden</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>TÜV-06</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => openTarget("TÜV-03 ohne Änderung")} style={secondaryButton}>Abbrechen</button>
            <button onClick={save} style={dangerButton}>Massnahme speichern</button>
          </div>
        </div>

        <Card title="1 · Betroffene Position">
          <div style={{ display: "flex", justifyContent: "space-between", gap: 14 }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600, color: "#1a1a18" }}>12l Stahlflasche gelb</div>
              <div style={{ fontSize: 12, color: "#888780", marginTop: 4 }}>
                SN 123456 · INV INT-0047 · Auftrag TUV-2026-0007 · Prüfdatum 06.05.2026
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", justifyContent: "flex-end" }}>
              <Pill bg="#FCEBEB" color="#A32D2D">failed</Pill>
              <Pill bg="#FAEEDA" color="#BA7517">gesperrt</Pill>
            </div>
          </div>
        </Card>

        <Card title="2 · Mangel / Nacharbeit">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 12 }}>
            <Field label="Grundkategorie *">
              <select value={category} onChange={(event) => setCategory(event.target.value)} style={fieldStyle}>
                {categories.map((item) => <option key={item}>{item}</option>)}
              </select>
            </Field>
            <Field label="Schweregrad *">
              <select value={severity} onChange={(event) => setSeverity(event.target.value)} style={fieldStyle}>
                {severities.map((item) => <option key={item}>{item}</option>)}
              </select>
            </Field>
            <Field label="Nacharbeit möglich *">
              <select value={reworkPossible} onChange={(event) => setReworkPossible(event.target.value)} style={fieldStyle}>
                <option>ja</option>
                <option>nein</option>
                <option>unklar</option>
              </select>
            </Field>
          </div>
          <Field label="Beschreibung *">
            <textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={3} style={{ ...fieldStyle, resize: "vertical" }} />
          </Field>
        </Card>

        <Card title="3 · Nächste Massnahme">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
            {Object.entries(actions).map(([key, item]) => (
              <button
                key={key}
                onClick={() => setNextAction(key)}
                style={{
                  padding: 10,
                  borderRadius: 8,
                  border: nextAction === key ? `1.5px solid ${item.color}` : "1px solid #D3D1C7",
                  background: nextAction === key ? item.bg : "#fff",
                  color: nextAction === key ? item.color : "#5F5E5A",
                  cursor: "pointer",
                  fontWeight: 600,
                  fontSize: 11,
                }}
              >
                {item.label}
              </button>
            ))}
          </div>
        </Card>

        <Card title="4 · Status-Auswirkung">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill bg="#FCEBEB" color="#A32D2D">needs_review</Pill>
            <Pill bg="#FCEBEB" color="#A32D2D">{isRetire ? "retired" : "inactive"}</Pill>
            <Pill bg="#FAEEDA" color="#BA7517">Workflow gesperrt</Pill>
          </div>
          <div style={{ fontSize: 12, color: action.color, lineHeight: 1.6 }}>{action.impact}</div>
        </Card>

        <Card title="5 · Pflichtnotiz / Wiedervorlage">
          <Field label="Pflichtnotiz *">
            <textarea value={note} onChange={(event) => setNote(event.target.value)} rows={3} style={{ ...fieldStyle, resize: "vertical" }} />
          </Field>
          <div style={{ marginTop: 12, width: 220 }}>
            <Field label="Wiedervorlage">
              <input type="date" value={followUpDate} onChange={(event) => setFollowUpDate(event.target.value)} style={fieldStyle} />
            </Field>
          </div>
        </Card>

        {isRetire && (
          <Card title="6 · Bestätigung Ausmustern">
            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12, color: "#A32D2D" }}>
              <input type="checkbox" checked={retireConfirmed} onChange={(event) => setRetireConfirmed(event.target.checked)} />
              <span>Ich bestätige, dass das Equipment dauerhaft aus dem aktiven Bestand entfernt wird.</span>
            </label>
          </Card>
        )}

        <Card title="Audit / Folgeaktion">
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>
            Massnahme, Statusänderung und Pflichtnotiz werden in Workflow-Historie und Audit-Log gespeichert. Bei erneuter Prüfung kann ein Folgeauftrag über TÜV-02 vorbereitet werden.
          </div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
            <button onClick={() => openTarget("TÜV-03 Prüfauftrag-Detail")} style={secondaryButton}>TÜV-03</button>
            <button onClick={() => openTarget("TÜV-02 Folgeauftrag vorbereiten")} style={outlineButton}>TÜV-02 Folgeauftrag</button>
            <button onClick={() => openTarget("TÜV-07 Prüfhistorie")} style={secondaryButton}>TÜV-07 Historie</button>
            <button onClick={() => openTarget("EQ-03 Equipment-Detail")} style={secondaryButton}>EQ-03</button>
          </div>
        </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> Ausmustern ist eine bewusste Entscheidung und benötigt eine zusätzliche Bestätigung. Standard bei failed ist needs_review + inactive.
        </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 secondaryButton = {
  padding: "8px 14px",
  fontSize: 12,
  background: "#fff",
  border: "1px solid #B4B2A9",
  borderRadius: 6,
  color: "#5F5E5A",
  cursor: "pointer",
};

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

const dangerButton = {
  padding: "8px 14px",
  fontSize: 12,
  background: "#A32D2D",
  border: "none",
  borderRadius: 6,
  color: "#fff",
  cursor: "pointer",
  fontWeight: 600,
};
