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",
  location: "Werkstatt",
  status: "in_progress",
  dueStatus: "due_soon",
  dueDate: "15.05.2026",
  assignedTo: "David",
  plannedDate: "2026-05-08",
  priority: "normal",
  costAmount: "",
  costCurrency: "CHF",
  costNote: "",
};

const existingNotes = [
  {
    type: "Startnotiz",
    text: "Kunde meldet leichtes Abblasen an der zweiten Stufe.",
    by: "David",
    at: "08.05.2026 · 13:40",
  },
  {
    type: "Bearbeitungsnotiz",
    text: "Sichtprüfung durchgeführt, Mitteldruckprüfung folgt.",
    by: "David",
    at: "08.05.2026 · 14:20",
  },
];

const statusStyles = {
  open: { label: "Offen", bg: "#E6F1FB", color: "#185FA5" },
  in_progress: { label: "In Arbeit", bg: "#EEEDFE", color: "#534AB7" },
  waiting_for_parts: { label: "Wartet", bg: "#FAEEDA", color: "#BA7517" },
  rework_required: { label: "Nacharbeit", bg: "#FCEBEB", color: "#A32D2D" },
};

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

const priorityLabels = {
  normal: "Normal",
  high: "Hoch",
  critical: "Kritisch",
};

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 IS04ServiceBearbeiten() {
  const [status, setStatus] = useState(service.status);
  const [assignedTo, setAssignedTo] = useState(service.assignedTo);
  const [plannedDate, setPlannedDate] = useState(service.plannedDate);
  const [priority, setPriority] = useState(service.priority);
  const [costAmount, setCostAmount] = useState(service.costAmount);
  const [costCurrency, setCostCurrency] = useState(service.costCurrency);
  const [costNote, setCostNote] = useState(service.costNote);
  const [newNote, setNewNote] = useState("");
  const [saved, setSaved] = useState(false);

  const changes = useMemo(() => {
    const list = [];
    if (status !== service.status) list.push(`Status: ${statusStyles[service.status].label} → ${statusStyles[status].label}`);
    if (assignedTo !== service.assignedTo) list.push(`Mitarbeiter: ${service.assignedTo} → ${assignedTo}`);
    if (plannedDate !== service.plannedDate) list.push(`Datum: ${service.plannedDate} → ${plannedDate}`);
    if (priority !== service.priority) list.push(`Priorität: ${priorityLabels[service.priority]} → ${priorityLabels[priority]}`);
    if (costAmount !== service.costAmount || costCurrency !== service.costCurrency || costNote !== service.costNote) list.push("Kosteninformationen geändert");
    if (newNote.trim()) list.push("Neue Bearbeitungsnotiz wird ergänzt");
    return list;
  }, [status, assignedTo, plannedDate, priority, costAmount, costCurrency, costNote, newNote]);

  const costInvalid = costAmount.trim() !== "" && Number(costAmount) < 0;
  const criticalNoteRecommended = priority === "critical" && !newNote.trim();
  const canSave = changes.length > 0 && !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, 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 bearbeiten</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>IS-04</span>
            {chip(statusStyles[status], statusStyles[status].label)}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => alert("→ IS-03: Abbrechen ohne Änderung")} style={secondaryButtonStyle}>Abbrechen</button>
            <button onClick={() => alert("→ IS-05: Service abschliessen")} style={secondaryButtonStyle}>IS-05</button>
            <button disabled={!canSave} onClick={() => { setSaved(true); }} style={canSave ? primaryButtonStyle : disabledPrimaryButtonStyle}>Speichern</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(dueStyles[service.dueStatus], dueStyles[service.dueStatus].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="Priorität" value={priorityLabels[service.priority]} />
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
          <div style={cardStyle}>
            <h2 style={sectionTitleStyle}>Bearbeitbare Felder</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Status">
                <select value={status} onChange={(e) => { setStatus(e.target.value); setSaved(false); }} style={inputStyle}>
                  <option value="open">Offen</option>
                  <option value="in_progress">In Arbeit</option>
                  <option value="waiting_for_parts">Wartet</option>
                  <option value="rework_required">Nacharbeit erforderlich</option>
                </select>
              </Field>
              <Field label="Verantwortlicher Mitarbeiter">
                <select value={assignedTo} onChange={(e) => { setAssignedTo(e.target.value); setSaved(false); }} style={inputStyle}>
                  <option>David</option>
                  <option>Maria</option>
                  <option>Nicht zugewiesen</option>
                </select>
              </Field>
              <Field label="Geplantes Datum">
                <input type="date" value={plannedDate} onChange={(e) => { setPlannedDate(e.target.value); setSaved(false); }} style={inputStyle} />
              </Field>
              <Field label="Priorität">
                <select value={priority} onChange={(e) => { setPriority(e.target.value); setSaved(false); }} style={inputStyle}>
                  <option value="normal">Normal</option>
                  <option value="high">Hoch</option>
                  <option value="critical">Kritisch</option>
                </select>
              </Field>
              <Field label="Kostenbetrag">
                <input value={costAmount} onChange={(e) => { setCostAmount(e.target.value); setSaved(false); }} placeholder="0.00" 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>
            </div>
            <Field label="Kostenbemerkung">
              <input value={costNote} onChange={(e) => { setCostNote(e.target.value); setSaved(false); }} placeholder="optional, z. B. Material oder Aufwand" style={inputStyle} />
            </Field>
            <Field label="Neue Bearbeitungsnotiz">
              <textarea value={newNote} onChange={(e) => { setNewNote(e.target.value); setSaved(false); }} placeholder="z. B. Mitteldruck geprüft, O-Ring ersetzt, wartet auf Teil..." style={{ ...inputStyle, height: 96, resize: "vertical" }} />
            </Field>

            {costInvalid && <Notice tone="danger" title="Kosten prüfen" text="Der Kostenbetrag darf nicht negativ sein." />}
            {criticalNoteRecommended && <Notice title="Notiz empfohlen" text="Bei kritischer Priorität sollte eine Bearbeitungsnotiz ergänzt werden." />}
            {saved && <Notice tone="success" title="Gespeichert" text="Die Änderung wurde simuliert gespeichert und würde in der Workflow-Historie erscheinen." />}
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Bestehende Notizen</h2>
              {existingNotes.map((note, index) => (
                <div key={`${note.type}-${index}`} style={{ background: "#F1EFE8", borderRadius: 8, padding: "10px 12px", marginBottom: index < existingNotes.length - 1 ? 10 : 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#888780", textTransform: "uppercase", letterSpacing: 0.4 }}>{note.type}</div>
                  <div style={{ fontSize: 12, color: "#1a1a18", marginTop: 5 }}>{note.text}</div>
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 5 }}>{note.at} · {note.by}</div>
                </div>
              ))}
            </div>

            <div style={cardStyle}>
              <h2 style={sectionTitleStyle}>Änderungsvorschau</h2>
              {changes.length === 0 ? (
                <div style={{ fontSize: 13, color: "#888780" }}>Es wurden noch keine Änderungen vorgenommen.</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {changes.map((change) => (
                    <div key={change} style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>{change}</div>
                  ))}
                  <div style={{ background: "#EAF3DE", color: "#3B6D11", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>Historieneintrag wird beim Speichern erzeugt.</div>
                </div>
              )}
              <div style={{ marginTop: 12, background: "#FAEEDA", border: "1px solid #FAC775", color: "#BA7517", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}>
                Kosten sind nur dokumentierende Serviceinformationen und erzeugen keine Rechnung.
              </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-04 bearbeitet laufende Vorgänge. Abgeschlossene Vorgänge werden nicht direkt geändert, sondern später über IS-08 korrigiert.
        </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",
};
