import { useMemo, useState } from "react";

const statusOptions = {
  draft: { label: "draft", bg: "#FAEEDA", color: "#BA7517", detail: "Auftrag vorbereitet, noch nicht eingereicht." },
  submitted: { label: "submitted", bg: "#EEEDFE", color: "#534AB7", detail: "Auftrag bei Prüfstelle / Dienstleister eingereicht." },
  in_progress: { label: "in_progress", bg: "#E6F1FB", color: "#185FA5", detail: "Prüfung läuft oder Rückmeldung steht aus." },
  passed: { label: "passed", bg: "#EAF3DE", color: "#3B6D11", detail: "Prüfung abgeschlossen, Ergebnisse plausibilisieren." },
  failed: { label: "failed", bg: "#FCEBEB", color: "#A32D2D", detail: "Mindestens eine Position nicht bestanden." },
  rework_required: { label: "rework_required", bg: "#FAEEDA", color: "#BA7517", detail: "Nacharbeit erforderlich." },
  cancelled: { label: "cancelled", bg: "#F1EFE8", color: "#5F5E5A", detail: "Auftrag storniert." },
};

const allowedTransitions = {
  draft: ["submitted", "cancelled"],
  submitted: ["in_progress", "cancelled"],
  in_progress: ["passed", "failed", "rework_required", "cancelled"],
  passed: ["failed"],
  failed: ["rework_required"],
  rework_required: ["in_progress", "failed"],
  cancelled: [],
};

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 TUEV04StatusAktualisieren() {
  const [currentStatus, setCurrentStatus] = useState("submitted");
  const [targetStatus, setTargetStatus] = useState("in_progress");
  const [note, setNote] = useState("Prüfung durch Dienstleister gestartet, Rückmeldung steht aus.");
  const [confirmed, setConfirmed] = useState(false);
  const [message, setMessage] = useState("");

  const target = statusOptions[targetStatus];
  const current = statusOptions[currentStatus];
  const allowed = allowedTransitions[currentStatus]?.includes(targetStatus);
  const critical = ["failed", "rework_required", "cancelled"].includes(targetStatus) || (currentStatus === "passed" && targetStatus !== "passed");

  const impact = useMemo(() => {
    if (targetStatus === "submitted") return "Operative Nutzung wird gesperrt oder markiert.";
    if (targetStatus === "in_progress") return "Sperrwirkung bleibt bestehen. Prüfergebnis kann in TÜV-05 erfasst werden.";
    if (targetStatus === "passed") return "Sperrwirkung kann nach Ergebnisprüfung aufgehoben werden.";
    if (targetStatus === "failed") return "Betroffene Positionen müssen in TÜV-06 dokumentiert werden. needs_review und inactive sind möglich.";
    if (targetStatus === "rework_required") return "Positionen bleiben gesperrt. Nacharbeit wird in TÜV-06 konkretisiert.";
    if (targetStatus === "cancelled") return "Sperrwirkung und Positionen müssen geprüft werden.";
    return "Statuswechsel vorbereiten.";
  }, [targetStatus]);

  function save() {
    if (targetStatus === currentStatus) {
      setMessage("Statuswechsel blockiert: Zielstatus entspricht aktuellem Status.");
      return;
    }
    if (!allowed) {
      setMessage(`Statuswechsel blockiert: ${currentStatus} → ${targetStatus} ist in V1 nicht zulässig.`);
      return;
    }
    if (critical && !note.trim()) {
      setMessage("Statuswechsel blockiert: Kritischer Status benötigt eine Pflichtnotiz.");
      return;
    }
    if (critical && !confirmed) {
      setMessage("Statuswechsel blockiert: Kritischer Status benötigt eine Bestätigung.");
      return;
    }
    setMessage(`Status gespeichert: ${currentStatus} → ${targetStatus}. Workflow-Historie und Audit-Log wurden fortgeschrieben.`);
    setCurrentStatus(targetStatus);
  }

  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>Status aktualisieren</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" }}>Status aktualisieren</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>TÜV-04</span>
          </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}>Status 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 · 3 Positionen</div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <Pill bg={current.bg} color={current.color}>{current.label}</Pill>
              <Pill bg="#FAEEDA" color="#BA7517">Nutzung gesperrt</Pill>
            </div>
          </div>
        </Card>

        <Card title="2 · Zielstatus wählen">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {Object.entries(statusOptions).map(([value, option]) => {
              const isAllowed = allowedTransitions[currentStatus]?.includes(value);
              const isCurrent = value === currentStatus;
              return (
                <button key={value} onClick={() => setTargetStatus(value)} disabled={isCurrent} style={{ padding: 12, borderRadius: 8, border: targetStatus === value ? `1.5px solid ${option.color}` : "1px solid #D3D1C7", background: targetStatus === value ? option.bg : isCurrent ? "#F1EFE8" : "#fff", color: isCurrent ? "#888780" : targetStatus === value ? option.color : isAllowed ? "#1a1a18" : "#B4B2A9", cursor: isCurrent ? "not-allowed" : "pointer", textAlign: "left" }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{option.label}</div>
                  <div style={{ fontSize: 10, marginTop: 6 }}>{isCurrent ? "aktuell" : isAllowed ? "zulässig" : "nicht zulässig"}</div>
                </button>
              );
            })}
          </div>
        </Card>

        <Card title="3 · Auswirkungen">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill bg={target.bg} color={target.color}>Zielstatus: {target.label}</Pill>
            <Pill bg={allowed ? "#EAF3DE" : "#FCEBEB"} color={allowed ? "#3B6D11" : "#A32D2D"}>{allowed ? "Statuswechsel zulässig" : "nicht zulässig"}</Pill>
            {critical && <Pill bg="#FAEEDA" color="#BA7517">kritisch</Pill>}
          </div>
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>{target.detail}<br />{impact}</div>
        </Card>

        <Card title="4 · Statusnotiz">
          <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={4} placeholder="Statusnotiz erfassen..." style={{ ...fieldStyle, resize: "vertical" }} />
          <div style={{ marginTop: 8, fontSize: 11, color: critical ? "#BA7517" : "#888780" }}>
            {critical ? "Pflicht bei failed, rework_required, cancelled und Status-Rückschritten." : "Optional, aber für Nachvollziehbarkeit empfohlen."}
          </div>
        </Card>

        <Card title="5 · Bestätigung bei kritischem Status">
          <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12, color: critical ? "#BA7517" : "#5F5E5A" }}>
            <input type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} />
            <span>Ich bestätige, dass dieser Statuswechsel Auswirkungen auf Sperrwirkung und weitere Bearbeitung haben kann.</span>
          </label>
        </Card>

        <Card title="6 · Audit / Workflow-Historie">
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>
            Beim Speichern wird ein append-only Verlaufseintrag geschrieben: <strong>{currentStatus} → {targetStatus}</strong> · David · 06.05.2026 11:45 · Statusnotiz. Ergebnisdaten einzelner Positionen werden nicht in TÜV-04 erfasst.
          </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> Zielstatus, Pflichtnotiz und Bestätigung beeinflussen die Validierung. Kritische Status verweisen fachlich auf TÜV-06.
        </div>
      </div>
    </div>
  );
}

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 secondaryButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
