import { useMemo, useState } from "react";

const EQUIPMENT = [
  {
    id: "eq-001",
    type: "cylinder",
    typeLabel: "Tauchflasche",
    name: "12l Stahlflasche gelb",
    manufacturer: "Luxfer",
    model: "12l Stahl",
    serial: "123456",
    inventory: "INT-0047",
    assignment: "internal",
    owner: "Tauchschule",
    location: "Lager A",
    status: "active",
    quality: "incomplete",
    sync: "pending_sync",
  },
  {
    id: "eq-002",
    type: "regulator",
    typeLabel: "Atemregler",
    name: "Atemregler Set A1",
    manufacturer: "Apeks",
    model: "XTX50",
    serial: "APX-7712",
    inventory: "REG-001",
    assignment: "customer",
    owner: "Max Muster",
    location: "Werkstatt",
    status: "active",
    quality: "complete",
    sync: "synced",
  },
  {
    id: "eq-003",
    type: "unknown",
    typeLabel: "Unbestimmt",
    name: "Unbestimmtes Teil #TMP-8831",
    manufacturer: "",
    model: "",
    serial: "",
    inventory: "TMP-8831",
    assignment: "unassigned",
    owner: "Unbestimmt",
    location: "Inventurbox",
    status: "active",
    quality: "needs_review",
    sync: "local_only",
  },
  {
    id: "eq-004",
    type: "other",
    typeLabel: "Sonstiges: Scooter",
    name: "Scooter Suex 1",
    manufacturer: "Suex",
    model: "XJ",
    serial: "SX-12345",
    inventory: "SCO-001",
    assignment: "internal",
    owner: "Tauchschule",
    location: "Lager B",
    status: "active",
    quality: "complete",
    sync: "conflict",
  },
  {
    id: "eq-005",
    type: "mask",
    typeLabel: "Maske",
    name: "Maske blau M",
    manufacturer: "Cressi",
    model: "Focus",
    serial: "",
    inventory: "MSK-014",
    assignment: "internal",
    owner: "Tauchschule",
    location: "Regal 2",
    status: "active",
    quality: "complete",
    sync: "synced",
  },
  {
    id: "eq-006",
    type: "computer",
    typeLabel: "Tauchcomputer",
    name: "Perdix 2 Schulgerät",
    manufacturer: "Shearwater",
    model: "Perdix 2",
    serial: "SW-9981",
    inventory: "COM-003",
    assignment: "internal",
    owner: "Tauchschule",
    location: "Ausgabe",
    status: "inactive",
    quality: "complete",
    sync: "synced",
  },
];

const typeOptions = [
  ["all", "Alle Typen"],
  ["cylinder", "Tauchflasche"],
  ["regulator", "Atemregler"],
  ["bcd", "Jacket / BCD"],
  ["computer", "Tauchcomputer"],
  ["suit", "Tauchanzug"],
  ["mask", "Maske"],
  ["fins", "Flossen"],
  ["compass", "Kompass"],
  ["lamp", "Lampe"],
  ["weight", "Blei / Bleisystem"],
  ["smb", "Boje / SMB"],
  ["other", "Sonstiges"],
  ["unknown", "Unbestimmt"],
];

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" },
  retired: { label: "Ausgemustert", bg: "#FCEBEB", color: "#A32D2D" },
  archived: { label: "Archiviert", bg: "#F1EFE8", color: "#5F5E5A" },
};

const syncStyles = {
  synced: { label: "Synced", bg: "#EAF3DE", color: "#3B6D11" },
  pending_sync: { label: "Sync offen", bg: "#FAEEDA", color: "#BA7517" },
  local_only: { label: "Nur lokal", bg: "#E6F1FB", color: "#185FA5" },
  conflict: { label: "Konflikt", bg: "#FCEBEB", color: "#A32D2D" },
};

const assignmentLabels = {
  internal: "Intern",
  customer: "Kunde",
  unassigned: "Unbestimmt",
};

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

export default function EQ01EquipmentListe() {
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [assignmentFilter, setAssignmentFilter] = useState("all");
  const [qualityFilter, setQualityFilter] = useState("all");
  const [syncFilter, setSyncFilter] = useState("all");
  const [selectedId, setSelectedId] = useState(null);

  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)) &&
        (typeFilter === "all" || item.type === typeFilter) &&
        (assignmentFilter === "all" || item.assignment === assignmentFilter) &&
        (qualityFilter === "all" || item.quality === qualityFilter) &&
        (syncFilter === "all" || item.sync === syncFilter);
    });
  }, [search, typeFilter, assignmentFilter, qualityFilter, syncFilter]);

  const counts = {
    total: EQUIPMENT.length,
    active: EQUIPMENT.filter((e) => e.status === "active").length,
    incomplete: EQUIPMENT.filter((e) => e.quality !== "complete").length,
    conflicts: EQUIPMENT.filter((e) => e.sync === "conflict").length,
    internal: EQUIPMENT.filter((e) => e.assignment === "internal").length,
    customer: EQUIPMENT.filter((e) => e.assignment === "customer").length,
    unknown: EQUIPMENT.filter((e) => e.assignment === "unassigned" || e.type === "unknown").length,
  };

  const statCards = [
    { label: "Aktiv", value: counts.active, bg: "#EAF3DE", color: "#3B6D11" },
    { label: "Unvollständig", value: counts.incomplete, bg: "#FAEEDA", color: "#BA7517" },
    { label: "Konflikte", value: counts.conflicts, bg: "#FCEBEB", color: "#A32D2D" },
    { label: "Intern", value: counts.internal, bg: "#E6F1FB", color: "#185FA5" },
    { label: "Kunden", value: counts.customer, bg: "#EEEDFE", color: "#534AB7" },
    { label: "Unbestimmt", value: counts.unknown, bg: "#F1EFE8", color: "#5F5E5A" },
  ];

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 680, 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: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>Equipment</span>
          <span style={{ color: "#888780" }}>Kunden</span>
          <span style={{ color: "#888780" }}>Workflows</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 }}>
            <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Equipment</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>EQ-01</span>
            <span style={{ background: "#D3D1C7", color: "#5F5E5A", fontSize: 11, padding: "2px 8px", borderRadius: 20 }}>{counts.total} total</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => alert("QR-Code scannen → Equipment öffnen")}
              style={{ padding: "8px 14px", fontSize: 13, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer", fontWeight: 500 }}>
              QR scannen
            </button>
            <button onClick={() => alert("→ EQ-02: Neues Equipment erfassen")}
              style={{ padding: "8px 16px", fontSize: 13, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 500 }}>
              + Neues Equipment
            </button>
          </div>
        </div>

        <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "10px 14px", marginBottom: 16 }}>
          <div style={{ fontSize: 10, fontWeight: 500, color: "#888780", marginBottom: 8, textTransform: "uppercase", letterSpacing: 0.5 }}>Übersicht</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 }}>
            {statCards.map((s) => (
              <button key={s.label}
                onClick={() => {
                  if (s.label === "Unvollständig") setQualityFilter("incomplete");
                  if (s.label === "Konflikte") setSyncFilter("conflict");
                  if (s.label === "Intern") setAssignmentFilter("internal");
                  if (s.label === "Kunden") setAssignmentFilter("customer");
                  if (s.label === "Unbestimmt") setAssignmentFilter("unassigned");
                }}
                style={{ background: s.bg, border: "none", borderRadius: 6, padding: "8px 10px", textAlign: "center", cursor: "pointer" }}>
                <div style={{ fontSize: 18, fontWeight: 500, color: s.color }}>{s.value}</div>
                <div style={{ fontSize: 10, color: s.color, marginTop: 1 }}>{s.label}</div>
              </button>
            ))}
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 150px 130px 140px 130px", gap: 10, marginBottom: 12 }}>
          <input value={search} onChange={(e) => setSearch(e.target.value)}
            placeholder="Suche: Name, Seriennummer, Inventar, Kunde..."
            style={{ padding: "7px 12px", fontSize: 13, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff", outline: "none" }} />
          <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)} style={selectStyle}>
            {typeOptions.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
          </select>
          <select value={assignmentFilter} onChange={(e) => setAssignmentFilter(e.target.value)} style={selectStyle}>
            <option value="all">Zuordnung</option>
            <option value="internal">Intern</option>
            <option value="customer">Kunde</option>
            <option value="unassigned">Unbestimmt</option>
          </select>
          <select value={qualityFilter} onChange={(e) => setQualityFilter(e.target.value)} style={selectStyle}>
            <option value="all">Datenqualität</option>
            <option value="complete">Vollständig</option>
            <option value="incomplete">Unvollständig</option>
            <option value="needs_review">Prüfung nötig</option>
          </select>
          <select value={syncFilter} onChange={(e) => setSyncFilter(e.target.value)} style={selectStyle}>
            <option value="all">Sync</option>
            <option value="synced">Synchronisiert</option>
            <option value="local_only">Nur lokal</option>
            <option value="pending_sync">Sync offen</option>
            <option value="conflict">Konflikt</option>
          </select>
        </div>

        <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
          <QuickFilter label="Unvollständig" onClick={() => setQualityFilter("incomplete")} />
          <QuickFilter label="Prüfung nötig" onClick={() => setQualityFilter("needs_review")} />
          <QuickFilter label="Nicht synchronisiert" onClick={() => setSyncFilter("pending_sync")} />
          <QuickFilter label="Intern" onClick={() => setAssignmentFilter("internal")} />
          <QuickFilter label="Kundenequipment" onClick={() => setAssignmentFilter("customer")} />
          <button onClick={() => { setSearch(""); setTypeFilter("all"); setAssignmentFilter("all"); setQualityFilter("all"); setSyncFilter("all"); }}
            style={{ fontSize: 11, padding: "5px 10px", background: "transparent", border: "1px solid #B4B2A9", borderRadius: 14, color: "#5F5E5A", cursor: "pointer" }}>
            Filter zurücksetzen
          </button>
        </div>

        <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1.4fr 1.2fr 1fr 1.3fr 1fr", padding: "10px 14px", background: "#F1EFE8", borderBottom: "1px solid #D3D1C7" }}>
            {["Typ / Name", "Hersteller / Modell", "SN / Inventar", "Zuordnung", "Status", "Aktionen"].map((h) => (
              <div key={h} style={{ fontSize: 11, fontWeight: 500, color: "#5F5E5A" }}>{h}</div>
            ))}
          </div>

          {filtered.length === 0 && (
            <div style={{ padding: "26px", textAlign: "center", color: "#888780", fontSize: 13 }}>Keine passenden Equipment-Datensätze gefunden.</div>
          )}

          {filtered.map((item, index) => {
            const isSelected = selectedId === item.id;
            const quality = qualityStyles[item.quality];
            const status = statusStyles[item.status];
            const sync = syncStyles[item.sync];
            return (
              <div key={item.id}
                onClick={() => setSelectedId(isSelected ? null : item.id)}
                style={{
                  display: "grid",
                  gridTemplateColumns: "1.6fr 1.4fr 1.2fr 1fr 1.3fr 1fr",
                  padding: "12px 14px",
                  borderBottom: index < filtered.length - 1 ? "1px solid #F1EFE8" : "none",
                  background: isSelected ? "#E6F1FB" : "#fff",
                  cursor: "pointer",
                  alignItems: "center",
                  gap: 8,
                }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "#1a1a18" }}>{item.name}</div>
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 2 }}>{item.typeLabel} · {item.location}</div>
                </div>
                <div style={{ fontSize: 12, color: "#5F5E5A" }}>
                  <div>{item.manufacturer || "—"}</div>
                  <div style={{ color: "#888780", marginTop: 2 }}>{item.model || "—"}</div>
                </div>
                <div style={{ fontSize: 11, color: "#5F5E5A" }}>
                  <div>{item.serial ? `SN ${item.serial}` : "SN —"}</div>
                  <div style={{ color: "#888780", marginTop: 2 }}>{item.inventory ? `INV ${item.inventory}` : "INV —"}</div>
                </div>
                <div>
                  {chip(item.assignment === "customer" ? { bg: "#EEEDFE", color: "#534AB7" } : item.assignment === "internal" ? { bg: "#E6F1FB", color: "#185FA5" } : { bg: "#F1EFE8", color: "#5F5E5A" }, assignmentLabels[item.assignment])}
                  <div style={{ fontSize: 10, color: "#888780", marginTop: 4 }}>{item.owner}</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 4 }}>
                  {chip(status, status.label)}
                  {chip(quality, quality.label)}
                  {chip(sync, sync.label)}
                </div>
                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                  <button onClick={(e) => { e.stopPropagation(); alert(`→ EQ-03: ${item.name}`); }} style={buttonStyle}>Öffnen</button>
                  <button onClick={(e) => { e.stopPropagation(); alert(`QR-Code für ${item.name}`); }} style={buttonStyle}>QR</button>
                  {item.quality !== "complete" && <button onClick={(e) => { e.stopPropagation(); alert(`→ EQ-04: ${item.name} vervollständigen`); }} style={warningButtonStyle}>Prüfen</button>}
                </div>
              </div>
            );
          })}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontSize: 11, color: "#888780" }}>
          <span>{filtered.length} von {EQUIPMENT.length} Datensätzen angezeigt</span>
          <span>V1: QR-Code aktiv · NFC nicht in V1 · Offline-Erfassung vorbereitet</span>
        </div>

        <div style={{ marginTop: 16, padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Suche, Filter und Schnellfilter sind funktional. Datensätze mit <code>unknown</code> oder unvollständiger Datenqualität sind nicht workflow-fähig. QR-Code ist V1-Umfang; NFC bleibt spätere Prüfoption.
        </div>
      </div>
    </div>
  );
}

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

const buttonStyle = {
  fontSize: 11,
  padding: "3px 8px",
  background: "transparent",
  border: "1px solid #B4B2A9",
  borderRadius: 4,
  cursor: "pointer",
  color: "#5F5E5A",
};

const warningButtonStyle = {
  fontSize: 11,
  padding: "3px 8px",
  background: "#FAEEDA",
  border: "1px solid #BA7517",
  borderRadius: 4,
  cursor: "pointer",
  color: "#BA7517",
};

function QuickFilter({ label, onClick }) {
  return (
    <button onClick={onClick}
      style={{ fontSize: 11, padding: "5px 10px", background: "#fff", border: "1px solid #D3D1C7", borderRadius: 14, color: "#5F5E5A", cursor: "pointer" }}>
      {label}
    </button>
  );
}
