// Transactions explorer — real transaction stream from the API.

const { useState: useTxnState, useMemo: useTxnMemo, useEffect: useTxnEffect } = React;

function formatAmount(n, cur) {
  const sym = { USD: "$", EUR: "€", GBP: "£", MXN: "MX$" }[cur] || "";
  return sym + Number(n || 0).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function formatDate(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  return d.toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" });
}

function TypePill({ type }) {
  const color = {
    payment: "info",
    transfer: "ok",
    cash_out: "warn",
    cash_in: "low",
    debit: "med",
    wire: "high",
    ach: "info",
    card: "med",
    atm: "warn",
    crypto: "low",
    cash: "low",
  }[type?.toLowerCase()] || "outline";
  return <span className={`pill ${color}`}>{type || "—"}</span>;
}

function TransactionsView({ data, initialQuery }) {
  const transactions = data?.transactions || window.TRANSACTIONS_API || [];
  const [page, setPage] = useTxnState(1);
  const [pageSize, setPageSize] = useTxnState(50);
  const [sortBy, setSortBy] = useTxnState("timestamp");
  const [filterType, setFilterType] = useTxnState("all");
  const [search, setSearch] = useTxnState("");
  const [selected, setSelected] = useTxnState(new Set());

  useTxnEffect(() => {
    if (initialQuery) { setSearch(initialQuery); setPage(1); }
  }, [initialQuery]);
  const [creating, setCreating] = useTxnState(false);
  const [submitting, setSubmitting] = useTxnState(false);
  const [manualSeverity, setManualSeverity] = useTxnState("high");
  const [manualTitle, setManualTitle] = useTxnState("");
  const [manualNote, setManualNote] = useTxnState("");
  const [manualStatus, setManualStatus] = useTxnState(null);

  const types = useTxnMemo(() => {
    const set = new Set(transactions.map(t => t.transaction_type).filter(Boolean));
    return Array.from(set).sort();
  }, [transactions]);

  const filtered = useTxnMemo(() => {
    let r = transactions;
    if (filterType !== "all") r = r.filter(t => t.transaction_type === filterType);
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      r = r.filter(t =>
        (t.external_id || "").toLowerCase().includes(q) ||
        (t.originator_id || "").toLowerCase().includes(q) ||
        (t.beneficiary_id || "").toLowerCase().includes(q) ||
        (t.originator_account || "").toLowerCase().includes(q) ||
        (t.beneficiary_account || "").toLowerCase().includes(q)
      );
    }
    r = [...r].sort((a, b) => {
      if (sortBy === "timestamp") return new Date(b.timestamp) - new Date(a.timestamp);
      if (sortBy === "amount") return Number(b.amount || 0) - Number(a.amount || 0);
      if (sortBy === "risk") return Number(b.risk_score || 0) - Number(a.risk_score || 0);
      return 0;
    });
    return r;
  }, [transactions, filterType, search, sortBy]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const paged = filtered.slice((safePage - 1) * pageSize, safePage * pageSize);

  const allPagedSelected = paged.length > 0 && paged.every(t => selected.has(t.id));

  const toggleSelect = (id) => {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelected(next);
  };

  const toggleAllPaged = () => {
    const next = new Set(selected);
    if (allPagedSelected) {
      paged.forEach(t => next.delete(t.id));
    } else {
      paged.forEach(t => next.add(t.id));
    }
    setSelected(next);
  };

  const clearSelection = () => setSelected(new Set());

  const createAlerts = async () => {
    if (selected.size === 0) return;
    setSubmitting(true);
    setManualStatus(null);
    try {
      const ids = Array.from(selected);
      await window.mossadApi.createManualAlerts({
        transaction_ids: ids,
        severity: manualSeverity,
        title: manualTitle.trim() || undefined,
        description: manualNote.trim() || undefined,
      });
      setManualStatus({ type: "ok", text: `Created 1 alert from ${ids.length} transaction${ids.length !== 1 ? "s" : ""}` });
      setSelected(new Set());
      if (data?.refresh) await data.refresh();
    } catch (err) {
      setManualStatus({ type: "error", text: "Failed to create alert: " + err.message });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ padding: 18, borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 12, gap: 10 }}>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>Transactions</h1>
          <span className="pill outline">{transactions.length.toLocaleString()} loaded</span>
          <div style={{ flex: 1 }} />
          {selected.size > 0 && (
            <span className="pill high" style={{ fontSize: 12 }}>{selected.size} selected</span>
          )}
          {selected.size > 0 && (
            <button className="btn sm primary" onClick={() => setCreating(true)}>
              <Icon.Flag size={11} /> Create alert
            </button>
          )}
          <button className="btn sm" onClick={data?.refresh} title="Refresh">
            <Icon.Refresh size={12} />
          </button>
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <input
            className="field"
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
            placeholder="Search ID, originator, beneficiary…"
            style={{ minWidth: 240, flex: 1 }}
          />
          <select className="field" value={filterType} onChange={e => { setFilterType(e.target.value); setPage(1); }} style={{ width: 150 }}>
            <option value="all">All types</option>
            {types.map(t => <option key={t} value={t}>{t}</option>)}
          </select>
          <select className="field" value={sortBy} onChange={e => { setSortBy(e.target.value); setPage(1); }} style={{ width: 150 }}>
            <option value="timestamp">Sort: Latest</option>
            <option value="amount">Sort: Amount</option>
            <option value="risk">Sort: Risk</option>
          </select>
          <select className="field" value={pageSize} onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }} style={{ width: 90 }}>
            <option value={25}>25</option>
            <option value={50}>50</option>
            <option value={100}>100</option>
          </select>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 28 }}>
                <input type="checkbox" checked={allPagedSelected} onChange={toggleAllPaged} />
              </th>
              <th style={{ width: 140 }}>Txn ID</th>
              <th style={{ width: 150 }}>Timestamp</th>
              <th style={{ width: 130 }}>Customer</th>
              <th style={{ width: 110 }}>Type</th>
              <th>Originator</th>
              <th>Beneficiary</th>
              <th className="right" style={{ width: 130 }}>Amount</th>
              <th style={{ width: 90 }}>Status</th>
              <th style={{ width: 80 }}>Risk</th>
              <th style={{ width: 90 }}>Fraud</th>
            </tr>
          </thead>
          <tbody>
            {paged.map(t => (
              <tr key={t.id} className={selected.has(t.id) ? "selected" : ""}>
                <td>
                  <input type="checkbox" checked={selected.has(t.id)} onChange={() => toggleSelect(t.id)} />
                </td>
                <td><span className="mono" style={{ fontSize: 11.5 }}>{t.external_id}</span></td>
                <td><span style={{ fontSize: 11.5, color: "var(--fg-2)" }}>{formatDate(t.timestamp)}</span></td>
                <td><span className="mono" style={{ color: "var(--accent)", fontWeight: 500 }}>{t.customer_id || "—"}</span></td>
                <td><TypePill type={t.transaction_type} /></td>
                <td>
                  <div style={{ fontSize: 12 }}>{t.originator_id}</div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-3)" }}>{t.originator_country}</div>
                </td>
                <td>
                  <div style={{ fontSize: 12 }}>{t.beneficiary_id}</div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-3)" }}>{t.beneficiary_country}</div>
                </td>
                <td className="right mono" style={{ fontWeight: 500 }}>{formatAmount(t.amount, t.currency)}</td>
                <td><span className="pill outline">{t.status}</span></td>
                <td>
                  <span className="mono" style={{ color: Number(t.risk_score || 0) >= 70 ? "var(--risk-high)" : "var(--fg-2)" }}>
                    {Math.round(Number(t.risk_score || 0))}
                  </span>
                </td>
                <td>
                  {t.payload?.is_fraud ? (
                    <span className="pill high">Fraud</span>
                  ) : t.payload?.is_flagged_fraud ? (
                    <span className="pill warn">Flagged</span>
                  ) : (
                    <span className="pill low">No</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {paged.length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--fg-3)" }}>
            No transactions match your filters.
          </div>
        )}
      </div>

      <div style={{
        display: "flex", alignItems: "center",
        padding: "8px 18px",
        borderTop: "1px solid var(--border)",
        background: "var(--bg)",
        fontSize: 11.5, color: "var(--fg-3)",
        gap: 8,
      }}>
        <span>Showing <b style={{ color: "var(--fg)" }}>{paged.length}</b> of <b style={{ color: "var(--fg)" }}>{filtered.length}</b></span>
        {selected.size > 0 && (
          <button className="btn ghost sm" onClick={clearSelection}>
            Clear selection ({selected.size})
          </button>
        )}
        <span style={{ flex: 1 }} />
        <button className="btn ghost sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={safePage <= 1}>
          <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Prev
        </button>
        <span>Page <b className="mono" style={{ color: "var(--fg)" }}>{safePage}</b> / <span className="mono">{totalPages}</span></span>
        <button className="btn ghost sm" onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={safePage >= totalPages}>
          Next <Icon.Chevron size={11} />
        </button>
      </div>

      {creating && (
        <div style={{
          position: "fixed", inset: 0, background: "rgba(0,0,0,0.35)",
          display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100,
        }} onClick={() => setCreating(false)}>
          <div className="card" style={{ width: 420, padding: 24 }} onClick={e => e.stopPropagation()}>
            <h3 style={{ margin: "0 0 6px" }}>Create manual alert</h3>
            <p style={{ margin: "0 0 16px", color: "var(--fg-3)", fontSize: 12.5 }}>
              {selected.size} transaction{selected.size !== 1 ? "s" : ""} selected · combined into 1 alert
            </p>
            <div style={{ marginBottom: 12 }}>
              <label style={{ display: "block", fontSize: 11.5, color: "var(--fg-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>Severity</label>
              <select className="field" value={manualSeverity} onChange={e => setManualSeverity(e.target.value)} style={{ width: "100%" }}>
                <option value="critical">Critical</option>
                <option value="high">High</option>
                <option value="medium">Medium</option>
                <option value="low">Low</option>
              </select>
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={{ display: "block", fontSize: 11.5, color: "var(--fg-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>Title (optional)</label>
              <input className="field" value={manualTitle} onChange={e => setManualTitle(e.target.value)} placeholder="e.g. Suspicious wire batch" style={{ width: "100%" }} />
            </div>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: 11.5, color: "var(--fg-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>Note (optional)</label>
              <textarea className="field" value={manualNote} onChange={e => setManualNote(e.target.value)} placeholder="Reason for manual alert…" style={{ width: "100%", minHeight: 60 }} />
            </div>
            {manualStatus && (
              <div style={{ marginBottom: 12, padding: 8, borderRadius: 4, fontSize: 12, background: manualStatus.type === "ok" ? "var(--risk-low-bg)" : "var(--risk-high-bg)", color: manualStatus.type === "ok" ? "var(--risk-low)" : "var(--risk-high)" }}>
                {manualStatus.text}
              </div>
            )}
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button className="btn" onClick={() => setCreating(false)} disabled={submitting}>Cancel</button>
              <button className="btn primary" onClick={createAlerts} disabled={submitting}>
                {submitting ? "Creating…" : "Create alert"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { TransactionsView });
