import { useMemo, useState } from "react";

const rows = [
  {
    id: "eq-001",
    name: "12l Stahlflasche gelb",
    serial: "123456",
    inventory: "INT-0047",
    location: "Lager A",
    assignment: "Intern",
    material: "Stahl",
    pressure: "232 bar",
    due: "2026-04-30",
    dueState: "overdue",
    days: -6,
    inspectionStatus: "none",
    quality: "complete",
    equipmentStatus: "active",
    sync: "synced",
  },
  {
    id: "eq-002",
    name: "10l Aluflasche silber",
    serial: "AL-9001",
    inventory: "INT-0052",
    location: "Lager B",
    assignment: "Kunde: Max Muster",
    material: "Aluminium",
    pressure: "200 bar",
    due: "2026-05-20",
    dueState: "due",
    days: 14,
    inspectionStatus: "none",
    quality: "complete",
    equipmentStatus: "active",
    sync: "synced",
  },
  {
    id: "eq-003",
    name: "15l Stahlflasche blau",
    serial: "15-ST-77",
    inventory: "INT-0063",
    location: "Werkstatt",
    assignment: "Intern",
    material: "Stahl",
    pressure: "232 bar",
    due: "2026-06-15",
    dueState: "soon",
    days: 40,
    inspectionStatus: "submitted",
    quality: "complete",
    equipmentStatus: "active",
    sync: "synced",
  },
  {
    id: "eq-004",
    name: "7l Stage Stahl",
    serial: "STAGE-07",
    inventory: "INT-0074",
    location: "Lager A",
    assignment: "Intern",
    material: "Stahl",
    pressure: "200 bar",
    due: "2026-05-25",
    dueState: "due",
    days: 19,
    inspectionStatus: "none",
    quality: "complete",
    equipmentStatus: "active",
    sync: "synced",
  },
  {
    id: "eq-005",
    name: "Unbestimmte Flasche #TMP-44",
    serial: "",
    inventory: "TMP-44",
    location: "Inventurbox",
    assignment: "Unbestimmt",
    material: "unbekannt",
    pressure: "unbekannt",
    due: "",
    dueState: "blocked",
    days: null,
    inspectionStatus: "none",
    quality: "incomplete",
    equipmentStatus: "unknown",
    sync: "pending_sync",
  },
  {
    id: "eq-006",
    name: "12l Stahlflasche rot",
    serial: "ST-RED-22",
    inventory: "INT-0080",
    location: "Lager C",
    assignment: "Intern",
    material: "Stahl",
    pressure: "232 bar",
    due: "2026-05-01",
    dueState: "overdue",
    days: -5,
    inspectionStatus: "none",
    quality: "needs_review",
    equipmentStatus: "active",
    sync: "conflict",
  },
];

const styles = {
  overdue: { bg: "#FCEBEB", color: "#A32D2D", label: "überfällig" },
  due: { bg: "#FAEEDA", color: "#BA7517", label: "fällig" },
  soon: { bg: "#E6F1FB", color: "#185FA5", label: "bald fällig" },
  valid: { bg: "#EAF3DE", color: "#3B6D11", label: "gültig" },
  blocked: { bg: "#FCEBEB", color: "#A32D2D", label: "blockiert" },
  complete: { bg: "#EAF3DE", color: "#3B6D11", label: "complete" },
  incomplete: { bg: "#FAEEDA", color: "#BA7517", label: "incomplete" },
  needs_review: { bg: "#FCEBEB", color: "#A32D2D", label: "needs_review" },
  none: { bg: "#EAF3DE", color: "#3B6D11", label: "kein Auftrag" },
  submitted: { bg: "#EEEDFE", color: "#534AB7", label: "submitted" },
  synced: { bg: "#EAF3DE", color: "#3B6D11", label: "synced" },
  pending_sync: { bg: "#FAEEDA", color: "#BA7517", label: "pending_sync" },
  conflict: { bg: "#FCEBEB", color: "#A32D2D", label: "conflict" },
};

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

function isSubmittable(row) {
  return row.equipmentStatus === "active"
    && row.quality === "complete"
    && row.sync !== "conflict"
    && row.inspectionStatus === "none";
}

function blockReason(row) {
  if (row.equipmentStatus !== "active") return "Typ/Status nicht einreichbar";
  if (row.quality !== "complete") return "prüfrelevante Daten fehlen";
  if (row.sync === "conflict") return "Sync-Konflikt";
  if (row.inspectionStatus !== "none") return "offener Prüfauftrag";
  return "einreichbar";
}

export default function TUEV01PrueffaelligeEquipmentListe() {
  const [dueFilter, setDueFilter] = useState("all");
  const [submitFilter, setSubmitFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [syncFilter, setSyncFilter] = useState("all");
  const [selectedIds, setSelectedIds] = useState(["eq-001", "eq-002", "eq-004"]);
  const [message, setMessage] = useState("");

  const filteredRows = useMemo(() => rows.filter((row) => {
    const submittable = isSubmittable(row);
    return (dueFilter === "all" || row.dueState === dueFilter)
      && (submitFilter === "all" || (submitFilter === "submittable" ? submittable : !submittable))
      && (statusFilter === "all" || row.inspectionStatus === statusFilter)
      && (syncFilter === "all" || row.sync === syncFilter);
  }), [dueFilter, submitFilter, statusFilter, syncFilter]);

  const stats = {
    overdue: rows.filter((r) => r.dueState === "overdue").length,
    due: rows.filter((r) => r.dueState === "due").length,
    soon: rows.filter((r) => r.dueState === "soon").length,
    submitted: rows.filter((r) => r.inspectionStatus !== "none").length,
    blocked: rows.filter((r) => !isSubmittable(r)).length,
    selected: selectedIds.length,
  };

  function toggle(row) {
    if (!isSubmittable(row)) return;
    setSelectedIds((current) => current.includes(row.id) ? current.filter((id) => id !== row.id) : [...current, row.id]);
  }

  function submitSelected() {
    if (selectedIds.length === 0) {
      setMessage("Keine Flaschen ausgewählt. Prüfung einreichen ist deaktiviert.");
      return;
    }
    setMessage(`Öffnet TÜV-02 als ${selectedIds.length > 1 ? "Sammel-Prüfauftrag" : "Einzel-Prüfauftrag"} mit ${selectedIds.length} Position(en).`);
  }

  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: "#888780" }}>Equipment</span>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>TÜV-Inspektion</span>
          <span style={{ color: "#888780" }}>Fristen</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" }}>TÜV-Inspektion</span><span style={{ margin: "0 6px" }}>›</span><span>Prüffällige Equipment-Liste</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" }}>Prüffällige Equipment-Liste</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>TÜV-01</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zur Navigation oder zum Fristen-Dashboard.")} style={secondaryButton}>Zurück</button>
            <button onClick={submitSelected} style={primaryButton}>Prüfung einreichen ({selectedIds.length})</button>
          </div>
        </div>

        <Card title="Kennzahlen">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 }}>
            <Stat label="Überfällig" value={stats.overdue} bg="#FCEBEB" color="#A32D2D" />
            <Stat label="Fällig" value={stats.due} bg="#FAEEDA" color="#BA7517" />
            <Stat label="Bald fällig" value={stats.soon} bg="#E6F1FB" color="#185FA5" />
            <Stat label="Eingereicht" value={stats.submitted} bg="#EEEDFE" color="#534AB7" />
            <Stat label="Blockiert" value={stats.blocked} bg="#FCEBEB" color="#A32D2D" />
            <Stat label="Ausgewählt" value={stats.selected} bg="#EAF3DE" color="#3B6D11" />
          </div>
        </Card>

        <Card title="Filter">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10 }}>
            <select value={dueFilter} onChange={(e) => setDueFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Fälligkeiten</option>
              <option value="overdue">überfällig</option>
              <option value="due">fällig</option>
              <option value="soon">bald fällig</option>
            </select>
            <select value={submitFilter} onChange={(e) => setSubmitFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle</option>
              <option value="submittable">einreichbar</option>
              <option value="blocked">blockiert</option>
            </select>
            <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} style={fieldStyle}>
              <option value="all">Alle Prüfstatus</option>
              <option value="none">kein Auftrag</option>
              <option value="submitted">submitted</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={() => { setDueFilter("all"); setSubmitFilter("all"); setStatusFilter("all"); setSyncFilter("all"); }} style={secondaryButton}>Filter zurück</button>
          </div>
        </Card>

        <Card title="Prüfliste" action={<span style={{ fontSize: 11, color: "#888780" }}>{filteredRows.length} Treffer</span>}>
          <div style={{ display: "grid", gap: 8 }}>
            {filteredRows.map((row) => {
              const submittable = isSubmittable(row);
              const selected = selectedIds.includes(row.id);
              return (
                <div key={row.id} style={{ display: "grid", gridTemplateColumns: "42px 1.6fr 1fr 1.2fr 1fr", gap: 10, alignItems: "center", border: "1px solid #F1EFE8", borderRadius: 8, padding: "10px 12px", background: "#fff" }}>
                  <button onClick={() => toggle(row)} disabled={!submittable} style={{ width: 24, height: 24, borderRadius: 5, border: submittable ? "1px solid #185FA5" : "1px solid #D3D1C7", background: selected ? "#185FA5" : submittable ? "#fff" : "#F1EFE8", color: "#fff", cursor: submittable ? "pointer" : "not-allowed" }}>{selected ? "✓" : ""}</button>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1a18" }}>{row.name}</div>
                    <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>SN {row.serial || "—"} · INV {row.inventory} · {row.location}</div>
                    <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>{row.assignment} · {row.material} · {row.pressure}</div>
                  </div>
                  <div>
                    <Pill value={row.dueState} />
                    <div style={{ fontSize: 11, color: "#888780", marginTop: 6 }}>{row.due || "kein Datum"}</div>
                    <div style={{ fontSize: 11, color: row.days < 0 ? "#A32D2D" : "#5F5E5A", marginTop: 3 }}>{row.days === null ? "—" : `${row.days} Tage`}</div>
                  </div>
                  <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
                    <Pill value={row.inspectionStatus} />
                    <Pill value={row.quality} />
                    <Pill value={row.sync} />
                    <Pill value={submittable ? "complete" : "blocked"} label={blockReason(row)} />
                  </div>
                  <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                    <button onClick={() => setMessage(`${row.name}: öffnet ${submittable ? "TÜV-02" : "EQ-04 / Prüfen"}.`)} style={submittable ? primaryMini : miniButton}>{submittable ? "TÜV-02" : "EQ-04"}</button>
                    <button onClick={() => setMessage(`${row.name}: öffnet EQ-03 Equipment-Detail.`)} style={miniButton}>EQ-03</button>
                    <button onClick={() => setMessage(`${row.name}: öffnet TÜV-07 Prüfhistorie.`)} style={miniButton}>Historie</button>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        <Card title="Sammel-Prüfauftrag">
          <div style={{ fontSize: 12, color: "#5F5E5A", lineHeight: 1.6 }}>
            {selectedIds.length} einreichbare Flasche(n) ausgewählt. TÜV-02 wird als {selectedIds.length > 1 ? "Sammel-Prüfauftrag" : "Einzel-Prüfauftrag"} geöffnet. Das Prüfergebnis wird später je Equipment-Position einzeln in TÜV-05 erfasst.
          </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> TÜV-01 verarbeitet in V1 nur Tauchflaschen / Druckbehälter. Blockierte Datensätze sind nicht auswählbar und zeigen den Sperrgrund.
        </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 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" };
