// Customers view — list customers derived from transactions and show their alerts/cases/transactions.

const { useState: useCustState } = React;

function formatAmount(n) {
  return "$" + 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 CustomerDetail({ customer, onBack }) {
  const [tab, setTab] = useCustState("transactions");
  const [transactions, setTransactions] = useCustState([]);
  const [alerts, setAlerts] = useCustState([]);
  const [cases, setCases] = useCustState([]);
  const [loading, setLoading] = useCustState(false);

  useEffectC(() => {
    let cancelled = false;
    const load = async () => {
      if (!customer?.customer_id || !window.mossadApi) return;
      setLoading(true);
      try {
        const [txns, alrts, cs] = await Promise.all([
          window.mossadApi.fetchCustomerTransactions(customer.customer_id, 100).catch(() => []),
          window.mossadApi.fetchCustomerAlerts(customer.customer_id, 100).catch(() => []),
          window.mossadApi.fetchCustomerCases(customer.customer_id, 100).catch(() => []),
        ]);
        if (!cancelled) {
          setTransactions(Array.isArray(txns) ? txns : []);
          setAlerts(Array.isArray(alrts) ? alrts.map(window.mossadApi.mapAlert) : []);
          setCases(Array.isArray(cs) ? cs.map(window.mossadApi.mapCase) : []);
        }
      } catch (err) {
        console.error("Failed to load customer details:", err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    load();
    return () => { cancelled = true; };
  }, [customer?.customer_id]);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ padding: 18, borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
          <button className="btn ghost sm" onClick={onBack}>
            <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Back to customers
          </button>
        </div>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>{customer.customer_id}</h1>
        <div style={{ display: "flex", gap: 16, marginTop: 8, fontSize: 12.5, color: "var(--fg-2)" }}>
          <span><b>{customer.transaction_count}</b> transactions</span>
          <span><b>{formatAmount(customer.total_volume)}</b> volume</span>
          <span>Last seen <b>{formatDate(customer.last_seen)}</b></span>
          <span><b>{customer.alert_count || 0}</b> alerts</span>
          <span><b>{customer.case_count || 0}</b> cases</span>
        </div>
      </div>

      <div style={{ display: "flex", gap: 0, borderBottom: "1px solid var(--border)", padding: "0 18px" }}>
        {["transactions", "alerts", "cases"].map(t => (
          <button key={t} className={`tab ${tab === t ? "active" : ""}`} onClick={() => setTab(t)} style={{ textTransform: "capitalize" }}>
            {t}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 18 }}>
        {loading && <div style={{ color: "var(--fg-3)", fontSize: 12 }}>Loading…</div>}
        {!loading && tab === "transactions" && (
          <table className="tbl">
            <thead>
              <tr>
                <th>Txn ID</th>
                <th>Timestamp</th>
                <th>Type</th>
                <th>Originator</th>
                <th>Beneficiary</th>
                <th className="right">Amount</th>
              </tr>
            </thead>
            <tbody>
              {transactions.map(t => (
                <tr key={t.id}>
                  <td className="mono">{t.external_id}</td>
                  <td>{formatDate(t.timestamp)}</td>
                  <td><span className="pill outline">{t.transaction_type}</span></td>
                  <td className="mono">{t.originator_id}</td>
                  <td className="mono">{t.beneficiary_id}</td>
                  <td className="right mono">{formatAmount(t.amount)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {!loading && tab === "alerts" && (
          <table className="tbl">
            <thead>
              <tr>
                <th>Alert ID</th>
                <th>Severity</th>
                <th>Typology</th>
                <th>Amount</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {alerts.map(a => (
                <tr key={a.id}>
                  <td className="mono">{a.external_id}</td>
                  <td><span className={`pill ${a.severity === "medium" ? "med" : a.severity || "low"}`}>{a.severity}</span></td>
                  <td>{a.typology}</td>
                  <td className="right mono">{formatAmount(a.amount)}</td>
                  <td><span className="pill outline">{a.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {!loading && tab === "cases" && (
          <table className="tbl">
            <thead>
              <tr>
                <th>Case ID</th>
                <th>Status</th>
                <th>Alerts</th>
                <th className="right">Amount</th>
              </tr>
            </thead>
            <tbody>
              {cases.map(c => (
                <tr key={c.id}>
                  <td className="mono">{c.external_id}</td>
                  <td><CaseStatusPill status={c.status} /></td>
                  <td className="mono">{c.alert_count}</td>
                  <td className="right mono">{formatAmount(c.total_amount)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function CaseStatusPill({ status }) {
  const map = {
    open: { cls: "pill info", label: "Open" },
    in_review: { cls: "pill med", label: "In review" },
    escalated: { cls: "pill high", label: "Escalated" },
    closed: { cls: "pill low", label: "Closed" },
  };
  const m = map[status] || { cls: "pill", label: status };
  return <span className={m.cls}>{m.label}</span>;
}

function CustomersView({ data, initialQuery }) {
  const initialCustomers = data?.customers || window.CUSTOMERS_API || [];
  const [customers, setCustomers] = useCustState(initialCustomers);
  const [search, setSearch] = useCustState("");
  const [loading, setLoading] = useCustState(false);
  const [selected, setSelected] = useCustState(null);

  useEffectC(() => {
    setCustomers(initialCustomers);
  }, [initialCustomers]);

  useEffectC(() => {
    if (initialQuery) setSearch(initialQuery);
  }, [initialQuery]);

  useEffectC(() => {
    let cancelled = false;
    const timer = setTimeout(async () => {
      if (!window.mossadApi) return;
      setLoading(true);
      try {
        const res = await window.mossadApi.fetchCustomers(500, search.trim());
        if (!cancelled) setCustomers(Array.isArray(res) ? res : []);
      } catch (err) {
        console.error("Failed to search customers:", err);
        if (!cancelled) setCustomers([]);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 250);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [search]);

  if (selected) {
    return <CustomerDetail customer={selected} onBack={() => setSelected(null)} />;
  }

  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 }}>Customers</h1>
          <span className="pill outline">{loading ? "Searching…" : `${customers.length.toLocaleString()} derived from transactions`}</span>
          <div style={{ flex: 1 }} />
          <button className="btn sm" onClick={data?.refresh} title="Refresh">
            <Icon.Refresh size={12} />
          </button>
        </div>
        <input
          className="field"
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Search customer ID across all transactions…"
          style={{ minWidth: 240, width: 360 }}
        />
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Customer ID</th>
              <th className="right">Transactions</th>
              <th className="right">Total volume</th>
              <th>Last seen</th>
              <th className="right">Alerts</th>
              <th className="right">Cases</th>
            </tr>
          </thead>
          <tbody>
            {customers.map(c => (
              <tr key={c.customer_id} onClick={() => setSelected(c)} style={{ cursor: "pointer" }}>
                <td><span className="mono" style={{ color: "var(--accent)", fontWeight: 500 }}>{c.customer_id}</span></td>
                <td className="right mono">{c.transaction_count.toLocaleString()}</td>
                <td className="right mono">{formatAmount(c.total_volume)}</td>
                <td>{formatDate(c.last_seen)}</td>
                <td className="right mono">{(c.alert_count ?? 0).toLocaleString()}</td>
                <td className="right mono">{(c.case_count ?? 0).toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {customers.length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--fg-3)" }}>
            No customers found.
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CustomersView });
