import { useMemo, useState } from "react";

const service = {
  id: "IS-2026-004",
  serviceType: "Atemregler-Service",
  serviceObject: "Atemregler",
  equipment: "Atemregler Set A1",
  manufacturer: "Apeks",
  model: "XTX50",
  serial: "APX-7712",
  inventory: "REG-001",
  owner: "Max Muster",
  status: "in_progress",
  dueStatus: "due_soon",
  dueDate: "15.05.2026",
  assignedTo: "David",
  plannedDate: "08.05.2026",
};

const resultOptions = {
  passed: { label: "Bestanden", targetStatus: "completed", bg: "#EAF3DE", color: "#3B6D11" },
  failed: { label: "Nicht bestanden", targetStatus: "rework_required", bg: "#FCEBEB", color: "#A32D2D" },
  rework_required: { label: "Nacharbeit erforderlich", targetStatus: "rework_required", bg: "#FCEBEB", color: "#A32D2D" },
  cancelled: { label: "Abgebrochen", targetStatus: "cancelled", bg: "#F1EFE8", color: "#5F5E5A" },
};

const statusStyles = {
  in_progress: { label: "In Arbeit", bg: "#EEEDFE", color: "#534AB7" },
  completed: { label: "Abgeschlossen", bg: "#EAF3DE", color: "#3B6D11" },
  rework_required: { label: "Nacharbeit", bg: "#FCEBEB", color: "#A32D2D" },
  cancelled: { label: "Abgebrochen", bg: "#F1EFE8", color: "#5F5E5A" },
};

const dueStyle = { label: "Bald fällig", bg: "#FAEEDA", color: "#BA7517" };

const chip = (style, label) => (
  <span style={{ background: style.bg, color: style.color, fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20, whiteSpace: "nowrap" }}>
    {label}
  </span>
);

export default function IS05ServiceAbschliessen() {
  const [result, setResult] = useState("passed");
  const [resultDate, setResultDate] = useState("2026-05-08");
  const [resultNote, setResultNote] = useState("");
  const [costAmount, setCostAmount] = useState("120.00");
  const [costCurrency, setCostCurrency] = useState("CHF");
  const [costNote, setCostNote] = useState("");
  const [nextServiceDate, setNextServiceDate] = useState("2027-05-08");
  const [confirmLock, setConfirmLock] = useState(false);
  const [completed, setCompleted] = useState(false);

  const selectedResult = resultOptions[result];
  const costInvalid = costAmount.trim() !== "" && Number(costAmount) < 0;
  const currencyMissing = costAmount.trim() !== "" && !costCurrency;
  const critical = result === "failed" || result === "rework_required";

  const checks = useMemo(() => [
    { label: "Ergebnis gesetzt", ok: Boolean(result) },
    { label: "Ergebnisdatum gesetzt", ok: Boolean(resultDate) },
    { label: "Ergebnisnotiz gesetzt", ok: resultNote.trim().length > 0 },
    { label: "Kosten plausibel", ok: !costInvalid && !currencyMissing },
    { label: "Sperrhinweis bestätigt", ok: confirmLock },
  ], [result, resultDate, resultNote, costInvalid, currencyMissing, confirmLock]);

  const canComplete = checks.every((check) => check.ok);

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 760, borderRadius: 8, overflow: "hidden" }}>
      <div style={{ background: "#1a1a18", padding: "10px 20px", fontSize: 13, display: "flex", alignItems: "center", gap: 16, borderRadius: "8px 8px 0 0" }}>
        <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 }}>Inhouse-Service</span>
          <span style={{ color: "#888780" }}>Fristen</span>
          <span style={{ color: "#D3D1C7", fontWeight: 500 }}>TSH · MA</span>
        </div>
      </div>

      <div style={{ padding: "20px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button onClick={() => alert("→ IS-03: zurück zum Detail")} style={backButtonStyle}>← Zurück</button>
            <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Service abschliessen</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>IS-05</span>
            {chip(statusStyles[service.status], statusStyles[service.status].label)}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => alert("→ IS-03: Abbrechen ohne Abschluss")} style={secondaryButtonStyle}>Abbrechen</button>
            <button disabled={!canComplete} onClick={() => setCompleted(true)} style={canComplete ? primaryButtonStyle : disabledPrimaryButtonStyle}>Service abschliessen</button>
          </div>
        </div>

        <div style={{ ...cardStyle, marginBottom: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 20 }}>
            <div>
              <div style={{ fontSize: 18, fontWeight: 700, color: "#1a1a18" }}>{service.id} · {service.serviceType}</div>
              <div style={{ fontSize: 13, color: "#5F5E5A", marginTop: 5 }}>{service.equipment} · {service.owner} · SN {service.serial} · INV {service.inventory}</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 10 }}>
                {chip(statusStyles[service.status], `Ausgang: ${statusStyles[service.status].label}`)}
                {chip(dueStyle, dueStyle.label)}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 120px)", gap: 12, fontSize: 12 }}>
              <Meta label="Verantwortlich" value={service.assignedTo} />
              <Meta label="Geplant" value={service.plannedDate} />
              <Meta label="Frist" value={service.dueDate} />
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
          <div style={cardStyle}>
            <h2 style={sectionTitleStyle}>Abschlussdaten</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Ergebnis *">
                <select value={result} onChange={(e) => { setResult(e.target.value); setCompleted(false); }} style={inputStyle}>
                  <option value="passed">Bestanden</option>
                  <option value="failed">Nicht bestanden</option>
                  <option value="rework_required">Nacharbeit erforderlich</option>
                  <option value="cancelled">Abgebrochen</option>
                </select>
              </Field>
              <Field label="Ergebnisdatum *">
                <input type="date" value={resultDate} onChange={(e) => { setResultDate(e.target.value); setCompleted(false); }} style={inputStyle} />
              </Field>
            </div>

            <Field label="Ergebnisnotiz *">
              <textarea value={resultNote} onChange={(e) => { setResultNote(e.target.value); setCompleted(false); }} placeholder="z. B. Service durchgeführt, Dichtheit geprüft, Funktion einwandfrei..." style={{ ...inputStyle, height: 96, resize: "vertical" }} />
            </Field>

            <div style={{ display: "grid", gridTemplateColumns: "220px 130px 1fr", gap: 12 }}>
              <Field label="Kostenbetrag">
                <input value={costAmount} onChange={(e) => { setCostAmount(e.target.value); setCompleted(false); }} placeholder="0.00" type="number" min="0" style={inputStyle} />
              </Field>
              <Field label="Währung">
                <select value={costCurrency} onChange={(e) => { setCostCurrency(e.target.value); setCompleted(false); }} style={inputStyle}>
                  <option>CHF</option>
                  <option>EUR</option>
                </select>
              </Field>
              <Field label="Kostenbemerkung">
                <input value={costNote} onChange={(e) => { setCostNote(e.target.value); setCompleted(false); }} placeholder="optional" style={inputStyle} />
              </Field>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 150px", gap: 12 }}>
              <Field label="Nächste Servicefrist">
                <input type="date" value={nextServiceDate} onChange={(e) => { setNextServiceDate(e.target.value); setCompleted(false); }} style={inputStyle} />
              </Field>
              <Field label="Intervall">
                <button onClick={() => setNextServiceDate("2027-05-08")} style={secondaryButtonStyle}>+12 Monate</button>
              </Field>
            </div>

            <label style={{ display: "flex", alignItems: "flex-start", gap: 10, marginTop: 8, background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, padding: "10px 12px", color: "#BA7517", fontSize: 12 }}>
              <input type="checkbox" checked={confirmLock} onChange={(e) => { setConfirmLock(e.target.checked); setCompleted(false); }} style={{ marginTop: 2 }} />
              <span>Ich bestätige, dass der Service nach dem Abschluss gegen direkte Änderungen gesperrt wird. Spätere Änderungen erfolgen als Korrektur.</span>
            </label>

            {critical && <Notice tone="danger" title="Kritisches Ergebnis" text="Dieses Ergebnis benötigt Nacharbeit oder eine fachliche Prüfung. Prüfe den Wechsel zu IS-06." />}
            {costInvalid && <Notice tone="danger" title="Kosten prüfen" text="Der Kostenbetrag darf nicht negativ sein." />}
            {completed && <Notice tone="success" title="Abschluss simuliert" text={`Der Workflow würde auf ${statusStyles[selectedResult.targetStatus].label} gesetzt und historisiert.`} />}
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Abschlussprüfung</h2>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {checks.map((check) => (
                  <div key={check.label} style={{ background: check.ok ? "#EAF3DE" : "#FAEEDA", color: check.ok ? "#3B6D11" : "#BA7517", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                    {check.ok ? "✓" : "!"} {check.label}
                  </div>
                ))}
              </div>
            </div>

            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Folgewirkung</h2>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ background: selectedResult.bg, color: selectedResult.color, borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                  Ergebnis: {selectedResult.label}
                </div>
                <div style={{ background: statusStyles[selectedResult.targetStatus].bg, color: statusStyles[selectedResult.targetStatus].color, borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                  Zielstatus: {statusStyles[selectedResult.targetStatus].label}
                </div>
                <div style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                  Workflow-Historie wird geschrieben.
                </div>
                <div style={{ background: "#F1EFE8", color: "#5F5E5A", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                  Nächste Frist wird für UC05 vorbereitet.
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 16, padding: "10px 14px", background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 8, fontSize: 11, color: "#185FA5" }}>
          <strong>Wireframe-Simulation:</strong> IS-05 finalisiert den Service. Danach ist der Vorgang gegen direkte Änderung geschützt; spätere Änderungen laufen über IS-08.
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 5, fontSize: 12, fontWeight: 600, color: "#5F5E5A", marginBottom: 10 }}>
      {label}
      {children}
    </label>
  );
}

function Meta({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: "#888780", textTransform: "uppercase", letterSpacing: 0.4 }}>{label}</div>
      <div style={{ fontSize: 13, color: "#1a1a18", marginTop: 4 }}>{value}</div>
    </div>
  );
}

function Notice({ tone = "warning", title, text }) {
  const style = tone === "danger"
    ? { bg: "#FCEBEB", border: "#F7C1C1", color: "#A32D2D" }
    : tone === "success"
      ? { bg: "#EAF3DE", border: "#C8E3B7", color: "#3B6D11" }
      : { bg: "#FAEEDA", border: "#FAC775", color: "#BA7517" };
  return (
    <div style={{ background: style.bg, border: `1px solid ${style.border}`, color: style.color, borderRadius: 8, padding: "9px 12px", fontSize: 12, marginTop: 8 }}>
      <strong>{title}:</strong> {text}
    </div>
  );
}

const cardStyle = {
  background: "#fff",
  border: "1px solid #D3D1C7",
  borderRadius: 8,
  padding: 18,
};

const sectionTitleStyle = {
  fontSize: 16,
  fontWeight: 600,
  color: "#1a1a18",
  margin: "0 0 14px 0",
};

const inputStyle = {
  padding: "8px 12px",
  fontSize: 13,
  border: "1px solid #B4B2A9",
  borderRadius: 6,
  background: "#fff",
  outline: "none",
};

const secondaryButtonStyle = {
  padding: "8px 12px",
  fontSize: 13,
  background: "#fff",
  border: "1px solid #B4B2A9",
  borderRadius: 6,
  color: "#5F5E5A",
  cursor: "pointer",
  fontWeight: 500,
};

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

const disabledPrimaryButtonStyle = {
  padding: "8px 14px",
  fontSize: 13,
  background: "#B4B2A9",
  border: "1px solid #B4B2A9",
  borderRadius: 6,
  color: "#fff",
  cursor: "not-allowed",
  fontWeight: 600,
};

const backButtonStyle = {
  padding: "6px 10px",
  fontSize: 12,
  background: "transparent",
  border: "1px solid #B4B2A9",
  borderRadius: 6,
  color: "#5F5E5A",
  cursor: "pointer",
};
