import { useMemo, useState } from "react";

const EQUIPMENT = [
  {
    id: "eq-reg-001",
    name: "Atemregler Set A1",
    type: "regulator",
    typeLabel: "Atemregler",
    manufacturer: "Apeks",
    model: "XTX50",
    serial: "APX-7712",
    inventory: "REG-001",
    ownerType: "customer",
    owner: "Max Muster",
    location: "Werkstatt",
    status: "active",
    quality: "complete",
    lastService: "14.05.2025",
    nextService: "15.05.2026",
    activeService: false,
  },
  {
    id: "eq-bcd-018",
    name: "Jacket Ocean Pro",
    type: "bcd",
    typeLabel: "Jacket / BCD",
    manufacturer: "Scubapro",
    model: "Ocean Pro",
    serial: "",
    inventory: "BCD-018",
    ownerType: "internal",
    owner: "Intern",
    location: "Lager A",
    status: "active",
    quality: "complete",
    lastService: "02.05.2025",
    nextService: "02.05.2026",
    activeService: true,
  },
  {
    id: "eq-com-003",
    name: "Perdix 2 Schulgerät",
    type: "computer",
    typeLabel: "Tauchcomputer",
    manufacturer: "Shearwater",
    model: "Perdix 2",
    serial: "SW-9981",
    inventory: "COM-003",
    ownerType: "internal",
    owner: "Intern",
    location: "Ausgabe",
    status: "active",
    quality: "complete",
    lastService: "—",
    nextService: "18.05.2026",
    activeService: false,
  },
  {
    id: "eq-lmp-009",
    name: "Lampe Backup 3",
    type: "other",
    typeLabel: "Sonstiges Equipment",
    manufacturer: "BigBlue",
    model: "Backup",
    serial: "BB-4401",
    inventory: "LMP-009",
    ownerType: "internal",
    owner: "Intern",
    location: "Werkstatt",
    status: "active",
    quality: "needs_review",
    lastService: "—",
    nextService: "unbekannt",
    activeService: false,
  },
  {
    id: "eq-old-001",
    name: "Archiviertes Jacket alt",
    type: "bcd",
    typeLabel: "Jacket / BCD",
    manufacturer: "Mares",
    model: "Dragon",
    serial: "",
    inventory: "BCD-001-ALT",
    ownerType: "internal",
    owner: "Intern",
    location: "Archiv",
    status: "archived",
    quality: "complete",
    lastService: "12.03.2024",
    nextService: "—",
    activeService: false,
  },
];

const serviceSuggestions = {
  regulator: { serviceType: "Atemregler-Service", serviceObject: "Atemregler" },
  bcd: { serviceType: "Jacket-Service", serviceObject: "Jacket / BCD" },
  computer: { serviceType: "Funktionsprüfung", serviceObject: "Tauchcomputer" },
  other: { serviceType: "Generischer Service", serviceObject: "Sonstiges Equipment" },
  unknown: { serviceType: "Generischer Service", serviceObject: "Unbekannt" },
};

const qualityStyles = {
  complete: { label: "Vollständig", bg: "#EAF3DE", color: "#3B6D11" },
  incomplete: { label: "Unvollständig", bg: "#FAEEDA", color: "#BA7517" },
  needs_review: { label: "Prüfung nötig", bg: "#FCEBEB", color: "#A32D2D" },
};

const statusStyles = {
  active: { label: "Aktiv", bg: "#EAF3DE", color: "#3B6D11" },
  inactive: { label: "Inaktiv", bg: "#F1EFE8", color: "#5F5E5A" },
  archived: { label: "Archiviert", bg: "#FCEBEB", color: "#A32D2D" },
};

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 IS02ServicevorgangStarten() {
  const [search, setSearch] = useState("");
  const [selectedId, setSelectedId] = useState("eq-reg-001");
  const selected = EQUIPMENT.find((item) => item.id === selectedId) || null;
  const suggestion = selected ? serviceSuggestions[selected.type] || serviceSuggestions.other : serviceSuggestions.other;
  const [serviceType, setServiceType] = useState("Atemregler-Service");
  const [serviceObject, setServiceObject] = useState("Atemregler");
  const [assignedTo, setAssignedTo] = useState("David");
  const [plannedDate, setPlannedDate] = useState("2026-05-08");
  const [priority, setPriority] = useState("normal");
  const [startStatus, setStartStatus] = useState("open");
  const [note, setNote] = useState("");

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return EQUIPMENT.filter((item) => {
      const haystack = [item.name, item.typeLabel, item.manufacturer, item.model, item.serial, item.inventory, item.owner, item.location].join(" ").toLowerCase();
      return !q || haystack.includes(q);
    });
  }, [search]);

  const selectEquipment = (item) => {
    setSelectedId(item.id);
    const next = serviceSuggestions[item.type] || serviceSuggestions.other;
    setServiceType(next.serviceType);
    setServiceObject(next.serviceObject);
  };

  const blocked = !selected || selected.status === "archived" || selected.status === "deleted";

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 720, 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-01: zurück zur Übersicht")} style={backButtonStyle}>← Zurück</button>
            <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Servicevorgang starten</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>IS-02</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => alert("Entwurf speichern")}
              style={{ padding: "8px 14px", fontSize: 13, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer", fontWeight: 500 }}>
              Entwurf speichern
            </button>
            <button disabled={blocked} onClick={() => alert(`→ IS-03: Neuer Service für ${selected?.name}`)}
              style={{ padding: "8px 16px", fontSize: 13, background: blocked ? "#B4B2A9" : "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: blocked ? "not-allowed" : "pointer", fontWeight: 500 }}>
              Service starten
            </button>
          </div>
        </div>

        <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "12px 18px", marginBottom: 16, display: "flex", alignItems: "center", gap: 20 }}>
          <Step active number="1" label="Equipment auswählen" />
          <div style={stepLineStyle} />
          <Step active={!!selected} number="2" label="Serviceangaben" />
          <div style={stepLineStyle} />
          <Step active={!blocked && !!selected} number="3" label="Bestätigung" />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.05fr", gap: 18 }}>
          <div style={cardStyle}>
            <h2 style={sectionTitleStyle}>1. Equipment auswählen</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 130px", gap: 8, marginBottom: 14 }}>
              <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Suche: Name, Seriennummer, Inventarnummer, Kunde..." style={inputStyle} />
              <button onClick={() => alert("QR-Code scannen → Equipment übernehmen")} style={secondaryButtonStyle}>QR scannen</button>
            </div>

            {selected && (
              <div style={{ border: "1px solid #185FA5", background: "#E6F1FB", borderRadius: 8, padding: 14, marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 600, color: "#1a1a18" }}>{selected.name}</div>
                    <div style={{ fontSize: 12, color: "#5F5E5A", marginTop: 4 }}>{selected.typeLabel} · {selected.manufacturer} {selected.model}</div>
                    <div style={{ fontSize: 12, color: "#5F5E5A", marginTop: 4 }}>SN {selected.serial || "—"} · INV {selected.inventory}</div>
                    <div style={{ fontSize: 12, color: "#5F5E5A", marginTop: 4 }}>{selected.ownerType === "customer" ? "Kunde" : "Intern"}: {selected.owner} · {selected.location}</div>
                  </div>
                  {chip({ bg: "#EAF3DE", color: "#3B6D11" }, "Ausgewählt")}
                </div>
                <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
                  {chip(statusStyles[selected.status], statusStyles[selected.status].label)}
                  {chip(qualityStyles[selected.quality], qualityStyles[selected.quality].label)}
                  {selected.activeService && chip({ bg: "#FCEBEB", color: "#A32D2D" }, "Aktiver Service vorhanden")}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 12, fontSize: 11, color: "#5F5E5A" }}>
                  <span>Letzter Service: <strong>{selected.lastService}</strong></span>
                  <span>Nächste Frist: <strong>{selected.nextService}</strong></span>
                </div>
              </div>
            )}

            <div style={{ fontSize: 11, fontWeight: 600, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 }}>Treffer</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {filtered.map((item) => (
                <button key={item.id} onClick={() => selectEquipment(item)}
                  style={{ textAlign: "left", background: selectedId === item.id ? "#F1EFE8" : "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "10px 12px", cursor: "pointer" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1a18" }}>{item.name}</div>
                      <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>{item.typeLabel} · {item.owner} · {item.inventory}</div>
                    </div>
                    {item.status === "archived" ? chip(statusStyles.archived, "Archiviert") : item.activeService ? chip({ bg: "#FCEBEB", color: "#A32D2D" }, "läuft") : null}
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div style={cardStyle}>
            <h2 style={sectionTitleStyle}>2. Serviceangaben</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Serviceart">
                <select value={serviceType} onChange={(e) => setServiceType(e.target.value)} style={inputStyle}>
                  <option>Atemregler-Service</option>
                  <option>Jacket-Service</option>
                  <option>Funktionsprüfung</option>
                  <option>Sichtprüfung</option>
                  <option>Generischer Service</option>
                </select>
              </Field>
              <Field label="Serviceobjekt">
                <select value={serviceObject} onChange={(e) => setServiceObject(e.target.value)} style={inputStyle}>
                  <option>Atemregler</option>
                  <option>Jacket / BCD</option>
                  <option>Tauchcomputer</option>
                  <option>Sonstiges Equipment</option>
                </select>
              </Field>
              <Field label="Verantwortlicher Mitarbeiter">
                <select value={assignedTo} onChange={(e) => setAssignedTo(e.target.value)} 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)} style={inputStyle} />
              </Field>
              <Field label="Priorität">
                <select value={priority} onChange={(e) => setPriority(e.target.value)} style={inputStyle}>
                  <option value="normal">Normal</option>
                  <option value="high">Hoch</option>
                  <option value="critical">Kritisch</option>
                </select>
              </Field>
              <Field label="Startstatus">
                <select value={startStatus} onChange={(e) => setStartStatus(e.target.value)} style={inputStyle}>
                  <option value="open">Offen</option>
                  <option value="in_progress">Direkt in Arbeit</option>
                </select>
              </Field>
            </div>

            <Field label="Startnotiz">
              <textarea value={note} onChange={(e) => setNote(e.target.value)} placeholder="z. B. Annahmehinweis, sichtbarer Mangel, Kundenwunsch..." style={{ ...inputStyle, height: 94, resize: "vertical" }} />
            </Field>

            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 12 }}>
              {selected?.activeService && (
                <Warning tone="danger" title="Aktiver Service vorhanden" text="Für dieses Equipment läuft bereits ein Servicevorgang. Prüfe zuerst den bestehenden Vorgang." />
              )}
              {selected?.quality === "needs_review" && (
                <Warning tone="danger" title="Stammdaten prüfen" text="Dieser Equipment-Datensatz benötigt eine Prüfung. Der Service kann fachlich eingeschränkt sein." />
              )}
              {selected?.status === "archived" && (
                <Warning tone="danger" title="Equipment archiviert" text="Für archiviertes Equipment darf kein neuer Servicevorgang gestartet werden." />
              )}
              {!selected && <Warning title="Kein Equipment ausgewählt" text="Wähle zuerst ein Equipment aus oder scanne einen QR-Code." />}
              {selected && !blocked && !selected.activeService && selected.quality === "complete" && (
                <Warning tone="info" title="Workflow-Vorschau" text={`Nach dem Start wird IS-03 für ${selected.name} geöffnet.`} />
              )}
            </div>

            <div style={{ marginTop: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <button onClick={() => alert("→ IS-01: Abbrechen")} style={secondaryButtonStyle}>Abbrechen</button>
              <button disabled={blocked} onClick={() => alert(`→ IS-03: ${serviceType} für ${selected?.name}`)} style={{ ...primaryButtonStyle, background: blocked ? "#B4B2A9" : "#185FA5", cursor: blocked ? "not-allowed" : "pointer" }}>
                Service starten
              </button>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 16, padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Equipment-Auswahl, Servicevorschlag und Warnhinweise sind funktional. Neue Serviceobjekte bleiben über den generischen Workflow erweiterbar.
        </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 Step({ active, number, label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{ width: 26, height: 26, borderRadius: "50%", background: active ? "#185FA5" : "#D3D1C7", color: active ? "#fff" : "#5F5E5A", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700 }}>{number}</div>
      <span style={{ fontSize: 13, fontWeight: active ? 600 : 400, color: active ? "#1a1a18" : "#5F5E5A" }}>{label}</span>
    </div>
  );
}

function Warning({ tone = "warning", title, text }) {
  const styles = tone === "danger"
    ? { bg: "#FCEBEB", border: "#F7C1C1", color: "#A32D2D" }
    : tone === "info"
      ? { bg: "#E6F1FB", border: "#B5D4F4", color: "#185FA5" }
      : { bg: "#FAEEDA", border: "#FAC775", color: "#BA7517" };
  return (
    <div style={{ background: styles.bg, border: `1px solid ${styles.border}`, borderRadius: 8, padding: "10px 12px", color: styles.color }}>
      <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 3 }}>{title}</div>
      <div style={{ fontSize: 12 }}>{text}</div>
    </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: "9px 16px",
  fontSize: 13,
  border: "none",
  borderRadius: 6,
  color: "#fff",
  fontWeight: 600,
};

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

const stepLineStyle = {
  flex: 1,
  height: 2,
  background: "#D3D1C7",
};
