import { useMemo, useState } from "react";

const original = {
  id: "IS-2026-004",
  serviceType: "Atemregler-Service",
  equipment: "Atemregler Set A1",
  owner: "Max Muster",
  result: "passed",
  resultDate: "2026-05-08",
  resultNote: "Service durchgeführt, Dichtheit geprüft, Funktion einwandfrei.",
  costAmount: "120.00",
  costCurrency: "CHF",
  nextServiceDate: "2027-05-08",
};

const resultLabels = {
  passed: "Bestanden",
  failed: "Nicht bestanden",
  rework_required: "Nacharbeit erforderlich",
  cancelled: "Abgebrochen",
};

export default function IS08KorrekturAbgeschlossenerService() {
  const [reason, setReason] = useState("");
  const [result, setResult] = useState(original.result);
  const [resultDate, setResultDate] = useState(original.resultDate);
  const [resultNote, setResultNote] = useState(original.resultNote);
  const [costAmount, setCostAmount] = useState(original.costAmount);
  const [costCurrency, setCostCurrency] = useState(original.costCurrency);
  const [nextServiceDate, setNextServiceDate] = useState(original.nextServiceDate);
  const [confirmed, setConfirmed] = useState(false);
  const [saved, setSaved] = useState(false);

  const changes = useMemo(() => {
    const list = [];
    if (result !== original.result) list.push(["Ergebnis", resultLabels[original.result], resultLabels[result]]);
    if (resultDate !== original.resultDate) list.push(["Ergebnisdatum", original.resultDate, resultDate]);
    if (resultNote !== original.resultNote) list.push(["Ergebnisnotiz", original.resultNote, resultNote]);
    if (costAmount !== original.costAmount || costCurrency !== original.costCurrency) list.push(["Kosten", `${original.costAmount} ${original.costCurrency}`, `${costAmount} ${costCurrency}`]);
    if (nextServiceDate !== original.nextServiceDate) list.push(["Nächste Servicefrist", original.nextServiceDate, nextServiceDate]);
    return list;
  }, [result, resultDate, resultNote, costAmount, costCurrency, nextServiceDate]);

  const costInvalid = costAmount.trim() !== "" && Number(costAmount) < 0;
  const canSave = reason.trim().length > 0 && changes.length > 0 && confirmed && !costInvalid;

  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 }}>
        <span style={{ fontWeight: 700, color: "#fff" }}>DiveLogix360</span>
        <span style={{ color: "#888780" }}>Tenant-Portal</span>
        <span style={{ marginLeft: "auto", color: "#fff", borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>Inhouse-Service</span>
      </div>

      <div style={{ padding: "20px 24px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button onClick={() => alert("→ IS-03")} style={backButtonStyle}>← Zurück</button>
            <h1 style={{ fontSize: 20, fontWeight: 500, margin: 0 }}>Korrektur abgeschlossener Service</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>IS-08</span>
            <span style={{ background: "#FAEEDA", color: "#BA7517", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>Korrektur</span>
          </div>
          <button disabled={!canSave} onClick={() => setSaved(true)} style={canSave ? primaryButtonStyle : disabledButtonStyle}>Korrektur speichern</button>
        </div>

        <div style={{ ...cardStyle, marginBottom: 18 }}>
          <div style={{ fontSize: 18, fontWeight: 700 }}>Original: {original.id} · {original.serviceType}</div>
          <div style={{ fontSize: 13, color: "#5F5E5A", marginTop: 5 }}>{original.equipment} · {original.owner} · abgeschlossen am {original.resultDate}</div>
          <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
            <span style={{ background: "#EAF3DE", color: "#3B6D11", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>Abgeschlossen</span>
            <span style={{ background: "#EAF3DE", color: "#3B6D11", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>{resultLabels[original.result]}</span>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
          <div style={cardStyle}>
            <h2 style={sectionTitleStyle}>Korrekturdaten</h2>
            <Field label="Korrekturgrund *">
              <textarea value={reason} onChange={(e) => { setReason(e.target.value); setSaved(false); }} placeholder="z. B. Ergebnisdatum falsch erfasst, Kostenbetrag korrigieren..." style={{ ...inputStyle, height: 82, resize: "vertical" }} />
            </Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Korrigiertes Ergebnis">
                <select value={result} onChange={(e) => { setResult(e.target.value); setSaved(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="Korrigiertes Ergebnisdatum">
                <input type="date" value={resultDate} onChange={(e) => { setResultDate(e.target.value); setSaved(false); }} style={inputStyle} />
              </Field>
            </div>
            <Field label="Korrigierte Ergebnisnotiz">
              <textarea value={resultNote} onChange={(e) => { setResultNote(e.target.value); setSaved(false); }} style={{ ...inputStyle, height: 82, resize: "vertical" }} />
            </Field>
            <div style={{ display: "grid", gridTemplateColumns: "180px 110px 1fr", gap: 12 }}>
              <Field label="Kostenbetrag">
                <input value={costAmount} onChange={(e) => { setCostAmount(e.target.value); setSaved(false); }} type="number" min="0" style={inputStyle} />
              </Field>
              <Field label="Währung">
                <select value={costCurrency} onChange={(e) => { setCostCurrency(e.target.value); setSaved(false); }} style={inputStyle}>
                  <option>CHF</option>
                  <option>EUR</option>
                </select>
              </Field>
              <Field label="Nächste Servicefrist">
                <input type="date" value={nextServiceDate} onChange={(e) => { setNextServiceDate(e.target.value); setSaved(false); }} style={inputStyle} />
              </Field>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Änderungsvorschau</h2>
              {changes.length === 0 ? <div style={{ fontSize: 13, color: "#888780" }}>Noch keine Änderung erkannt.</div> : changes.map(([field, before, after]) => (
                <div key={field} style={{ background: "#FAEEDA", color: "#BA7517", borderRadius: 8, padding: "8px 10px", fontSize: 12, marginBottom: 8 }}>
                  <strong>{field}</strong><br />{before} → {after}
                </div>
              ))}
              {!reason.trim() && <div style={{ background: "#FCEBEB", color: "#A32D2D", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>Korrekturgrund ist Pflicht.</div>}
            </div>
            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Bestätigung</h2>
              <label style={{ display: "flex", alignItems: "flex-start", gap: 10, background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, padding: "10px 12px", color: "#BA7517", fontSize: 12 }}>
                <input type="checkbox" checked={confirmed} onChange={(e) => { setConfirmed(e.target.checked); setSaved(false); }} style={{ marginTop: 2 }} />
                <span>Ich bestätige, dass Originaldaten erhalten bleiben und diese Änderung als Korrektur protokolliert wird.</span>
              </label>
              {costInvalid && <Notice tone="danger" title="Kosten prüfen" text="Der Kostenbetrag darf nicht negativ sein." />}
              {saved && <Notice tone="success" title="Korrektur simuliert" text="Die Korrektur würde historisiert und in IS-03 sowie IS-07 sichtbar gemacht." />}
            </div>
          </div>
        </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 Notice({ tone = "warning", title, text }) { const s = tone === "danger" ? { bg: "#FCEBEB", border: "#F7C1C1", color: "#A32D2D" } : { bg: "#EAF3DE", border: "#C8E3B7", color: "#3B6D11" }; return <div style={{ background: s.bg, border: `1px solid ${s.border}`, color: s.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 backButtonStyle = { padding: "6px 10px", fontSize: 12, background: "transparent", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
const primaryButtonStyle = { padding: "8px 14px", fontSize: 13, background: "#BA7517", border: "1px solid #BA7517", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
const disabledButtonStyle = { padding: "8px 14px", fontSize: 13, background: "#B4B2A9", border: "1px solid #B4B2A9", borderRadius: 6, color: "#fff", cursor: "not-allowed", fontWeight: 600 };
