import { useMemo, useState } from "react";

const records = [
  {
    id: "eq-003",
    name: "Unbestimmtes Teil #TMP-8831",
    type: "unknown",
    typeLabel: "Unbestimmt",
    location: "Inventurbox",
    assignment: "unassigned",
    quality: "incomplete",
    sync: "pending_sync",
    priority: "high",
    workflow: false,
    missing: ["Typ fehlt", "Zuordnung fehlt", "Identifikation unvollständig"],
    cause: "type_missing",
  },
  {
    id: "eq-001",
    name: "12l Stahlflasche gelb",
    type: "cylinder",
    typeLabel: "Tauchflasche",
    location: "Lager A",
    assignment: "internal",
    quality: "needs_review",
    sync: "synced",
    priority: "medium",
    workflow: false,
    missing: ["Nächste Prüfung fehlt", "Ventiltyp prüfen", "Normreferenz fehlt"],
    cause: "detail_missing",
  },
  {
    id: "eq-004",
    name: "Scooter Suex 1",
    type: "other",
    typeLabel: "Sonstiges: Scooter",
    location: "Lager B",
    assignment: "internal",
    quality: "needs_review",
    sync: "conflict",
    priority: "high",
    workflow: false,
    missing: ["Sync-Konflikt", "Typisierung prüfen"],
    cause: "sync_conflict",
  },
  {
    id: "eq-005",
    name: "Maske blau M",
    type: "mask",
    typeLabel: "Maske",
    location: "Regal 2",
    assignment: "internal",
    quality: "incomplete",
    sync: "synced",
    priority: "low",
    workflow: true,
    missing: ["Hersteller empfohlen", "optionale Notiz offen"],
    cause: "recommended_missing",
  },
  {
    id: "eq-006",
    name: "Atemregler Set A1",
    type: "regulator",
    typeLabel: "Atemregler",
    location: "Werkstatt",
    assignment: "customer",
    quality: "incomplete",
    sync: "synced",
    priority: "medium",
    workflow: false,
    missing: ["Serviceintervall fehlt", "letzte Revision fehlt"],
    cause: "detail_missing",
  },
];

const pillStyles = {
  incomplete: { bg: "#FAEEDA", color: "#BA7517", label: "incomplete" },
  needs_review: { bg: "#FCEBEB", color: "#A32D2D", label: "needs_review" },
  synced: { bg: "#EAF3DE", color: "#3B6D11", label: "synced" },
  pending_sync: { bg: "#FAEEDA", color: "#BA7517", label: "pending_sync" },
  conflict: { bg: "#FCEBEB", color: "#A32D2D", label: "conflict" },
  high: { bg: "#FCEBEB", color: "#A32D2D", label: "hoch" },
  medium: { bg: "#FAEEDA", color: "#BA7517", label: "mittel" },
  low: { bg: "#EAF3DE", color: "#3B6D11", label: "niedrig" },
};

function Pill({ value, label }) {
  const style = pillStyles[value] || { bg: "#F1EFE8", color: "#5F5E5A", label: value };
  return <span style={{ background: style.bg, color: style.color, borderRadius: 999, padding: "3px 9px", fontSize: 11, fontWeight: 600 }}>{label || style.label}</span>;
}

function Card({ title, children, action }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px", marginBottom: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5 }}>{title}</div>
        {action}
      </div>
      {children}
    </div>
  );
}

export default function EQ10UnvollstaendigeDatensaetzePruefen() {
  const [typeFilter, setTypeFilter] = useState("all");
  const [causeFilter, setCauseFilter] = useState("all");
  const [priorityFilter, setPriorityFilter] = useState("all");
  const [syncFilter, setSyncFilter] = useState("all");
  const [workflowOnly, setWorkflowOnly] = useState(true);
  const [message, setMessage] = useState("");

  const filtered = useMemo(() => records.filter((record) => {
    return (typeFilter === "all" || record.type === typeFilter)
      && (causeFilter === "all" || record.cause === causeFilter)
      && (priorityFilter === "all" || record.priority === priorityFilter)
      && (syncFilter === "all" || record.sync === syncFilter)
      && (!workflowOnly || !record.workflow);
  }), [typeFilter, causeFilter, priorityFilter, syncFilter, workflowOnly]);

  const stats = {
    incomplete: records.filter((r) => r.quality === "incomplete").length,
    review: records.filter((r) => r.quality === "needs_review").length,
    unknown: records.filter((r) => r.type === "unknown").length,
    unassigned: records.filter((r) => r.assignment === "unassigned").length,
    conflict: records.filter((r) => r.sync === "conflict").length,
    blocked: records.filter((r) => !r.workflow).length,
  };

  function action(record, target) {
    setMessage(`${record.name}: öffnet ${target}. Nach Bearbeitung wird der Datensatz neu bewertet.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 820, 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: "#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: "18px 24px" }}>
        <div style={{ fontSize: 12, color: "#888780", marginBottom: 12 }}>
          <span style={{ color: "#185FA5" }}>Equipment</span><span style={{ margin: "0 6px" }}>›</span><span>Unvollständige Datensätze</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 500, color: "#1a1a18" }}>Unvollständige Datensätze prüfen</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>EQ-10</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zu EQ-01.")} style={secondaryButton}>Zurück</button>
            <button onClick={() => setMessage("Prüfliste aktualisiert.")} style={primaryButton}>Aktualisieren</button>
          </div>
        </div>

        <Card title="Kennzahlen">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 }}>
            <Stat label="Unvollständig" value={stats.incomplete} bg="#FAEEDA" color="#BA7517" />
            <Stat label="Prüfung nötig" value={stats.review} bg="#FCEBEB" color="#A32D2D" />
            <Stat label="unknown" value={stats.unknown} bg="#F1EFE8" color="#5F5E5A" />
            <Stat label="unassigned" value={stats.unassigned} bg="#EEEDFE" color="#534AB7" />
            <Stat label="Konflikt" value={stats.conflict} bg="#FCEBEB" color="#A32D2D" />
            <Stat label="kein Workflow" value={stats.blocked} bg="#FCEBEB" color="#A32D2D" />
          </div>
        </Card>

        <Card title="Filter">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10 }}>
            <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Typen</option>
              <option value="unknown">unknown</option>
              <option value="cylinder">Tauchflasche</option>
              <option value="regulator">Atemregler</option>
              <option value="other">other</option>
              <option value="mask">Maske</option>
            </select>
            <select value={causeFilter} onChange={(e) => setCauseFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Ursachen</option>
              <option value="type_missing">Typ fehlt</option>
              <option value="detail_missing">Detaildaten fehlen</option>
              <option value="sync_conflict">Sync-Konflikt</option>
              <option value="recommended_missing">Empfohlene Felder</option>
            </select>
            <select value={priorityFilter} onChange={(e) => setPriorityFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Prioritäten</option>
              <option value="high">hoch</option>
              <option value="medium">mittel</option>
              <option value="low">niedrig</option>
            </select>
            <select value={syncFilter} onChange={(e) => setSyncFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Sync</option>
              <option value="synced">synced</option>
              <option value="pending_sync">pending_sync</option>
              <option value="conflict">conflict</option>
            </select>
            <button onClick={() => setWorkflowOnly(!workflowOnly)} style={workflowOnly ? warningButton : secondaryButton}>{workflowOnly ? "nur nicht WF" : "alle anzeigen"}</button>
          </div>
        </Card>

        <Card title="Prüfliste" action={<span style={{ fontSize: 11, color: "#888780" }}>{filtered.length} Treffer</span>}>
          <div style={{ display: "grid", gap: 8 }}>
            {filtered.map((record) => (
              <div key={record.id} style={{ display: "grid", gridTemplateColumns: "1.3fr 1.6fr 1fr 0.8fr 1fr", gap: 10, alignItems: "center", border: "1px solid #F1EFE8", borderRadius: 8, padding: "10px 12px" }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1a18" }}>{record.name}</div>
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>{record.typeLabel} · {record.location}</div>
                </div>
                <div style={{ fontSize: 11, color: record.priority === "high" ? "#A32D2D" : "#BA7517" }}>
                  {record.missing.map((m) => <div key={m}>• {m}</div>)}
                </div>
                <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
                  <Pill value={record.quality} />
                  <Pill value={record.sync} />
                  <Pill value={record.workflow ? "synced" : "conflict"} label={record.workflow ? "WF möglich" : "kein WF"} />
                </div>
                <div><Pill value={record.priority} /></div>
                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                  <button onClick={() => action(record, "EQ-04")} style={primaryMini}>EQ-04</button>
                  <button onClick={() => action(record, "EQ-03")} style={miniButton}>EQ-03</button>
                  <button onClick={() => action(record, "EQ-07")} style={miniButton}>Notiz</button>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card title="Bearbeitungslogik">
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>
            Vervollständigen öffnet EQ-04. Notiz öffnet EQ-07. Öffnen führt zu EQ-03. Nach erfolgreicher Vervollständigung verschwindet der Datensatz aus der Standardliste. unknown wird durch Typqualifizierung neu bewertet.
          </div>
        </Card>

        {message && <div style={{ padding: "10px 14px", background: "#EAF3DE", border: "1px solid #A8D08D", borderRadius: 8, fontSize: 12, color: "#3B6D11", marginBottom: 12 }}>{message}</div>}

        <div style={{ padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Filter und Workflow-Schalter verändern die Prüfliste. Die Aktionen simulieren Absprünge zu EQ-03, EQ-04 und EQ-07.
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value, bg, color }) {
  return (
    <div style={{ background: bg, color, borderRadius: 8, padding: "10px 8px", textAlign: "center" }}>
      <div style={{ fontSize: 18, fontWeight: 700 }}>{value}</div>
      <div style={{ fontSize: 10 }}>{label}</div>
    </div>
  );
}

const fieldStyle = { width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff" };
const primaryButton = { padding: "8px 14px", fontSize: 12, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
const secondaryButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
const warningButton = { padding: "8px 14px", fontSize: 12, background: "#FAEEDA", border: "1px solid #BA7517", borderRadius: 6, color: "#BA7517", cursor: "pointer", fontWeight: 600 };
const primaryMini = { padding: "4px 8px", fontSize: 10, background: "#185FA5", border: "none", borderRadius: 4, color: "#fff", cursor: "pointer" };
const miniButton = { padding: "4px 8px", fontSize: 10, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 4, color: "#5F5E5A", cursor: "pointer" };
