// Invoice → GRN Matching agent screen
const { useState: useStateIG } = React;

function InvoiceGrnAgent({ setRoute }) {
  const d = window.DEMO_DATA;
  const rows = d.invoiceMatches;
  const [tab, setTab] = useStateIG("overview");
  const [selected, setSelected] = useStateIG(null);
  const [query, setQuery] = useStateIG("");

  const filtered = rows.filter(r => {
    if (query && !`${r.vendor} ${r.po} ${r.invoice}`.toLowerCase().includes(query.toLowerCase())) return false;
    if (tab === "matched") return r.status === "matched";
    if (tab === "pending") return r.status === "awaiting" || r.status === "variance" || r.status === "pending";
    if (tab === "issues") return r.status === "issue";
    return true;
  });

  const counts = {
    overview: rows.length,
    matched: rows.filter(r => r.status === "matched").length,
    pending: rows.filter(r => ["awaiting", "variance", "pending"].includes(r.status)).length,
    issues: rows.filter(r => r.status === "issue").length,
  };

  const totalDiff = rows.reduce((s, r) => s + (r.invAmt - r.poAmt), 0);

  return (
    <div className="main wide" style={{padding: "20px 28px 80px"}}>
      <div className="page-head" style={{alignItems: "center", marginBottom: 20}}>
        <div className="row gap-md">
          <button className="btn ghost sm" onClick={() => setRoute({name: "dashboard"})}><Icon name="arrowLeft" size={14}/></button>
          <div>
            <div className="row gap-md items-center">
              <h1 style={{fontFamily: "Onest, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: "-0.025em", margin: 0}}>Invoice → GRN Matching</h1>
              <span className="pill ok"><span className="dot"></span>Operational</span>
            </div>
            <div className="page-sub" style={{marginTop: 4, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)"}}>PO · INVOICE · GRN · Three-way reconciliation</div>
          </div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="refresh" size={14}/> Refresh</button>
          <button className="btn"><Icon name="upload" size={14}/> Upload</button>
          <button className="btn"><Icon name="mail" size={14}/> Email Inbox</button>
        </div>
      </div>

      {/* Metric strip */}
      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(5, 1fr)", marginBottom: 20}}>
        <div className="kpi" style={{padding: "14px 18px"}}>
          <div className="kpi-label">Total Today</div>
          <div className="kpi-value" style={{fontSize: 28, marginTop: 6}}>{rows.length}</div>
        </div>
        <div className="kpi" style={{padding: "14px 18px"}}>
          <div className="kpi-label">Auto-Matched</div>
          <div className="kpi-value" style={{fontSize: 28, marginTop: 6, color: "var(--ok)"}}>{counts.matched}<span style={{fontSize: 14, color: "var(--muted)", marginLeft: 6, fontFamily: "Geist, sans-serif"}}>/{rows.length}</span></div>
        </div>
        <div className="kpi" style={{padding: "14px 18px"}}>
          <div className="kpi-label">Awaiting GRN</div>
          <div className="kpi-value" style={{fontSize: 28, marginTop: 6}}>{counts.pending}</div>
        </div>
        <div className="kpi" style={{padding: "14px 18px"}}>
          <div className="kpi-label">Issues</div>
          <div className="kpi-value" style={{fontSize: 28, marginTop: 6, color: counts.issues ? "var(--crit)" : "var(--ink)"}}>{counts.issues}</div>
        </div>
        <div className="kpi" style={{padding: "14px 18px"}}>
          <div className="kpi-label">Net Variance</div>
          <div className="kpi-value" style={{fontSize: 28, marginTop: 6, color: totalDiff > 0 ? "var(--warn)" : "var(--ok)"}}>{totalDiff > 0 ? "+" : ""}{fmt(totalDiff)}<span style={{fontSize: 13, color: "var(--muted)", marginLeft: 4, fontFamily: "Geist, sans-serif"}}>SAR</span></div>
        </div>
      </div>

      <div className="card">
        <div style={{padding: "14px 20px 0"}}>
          <div className="row between">
            <div className="tabs" style={{margin: 0, border: "none"}}>
              <button className={tab === "overview" ? "active" : ""} onClick={() => setTab("overview")}>Overview <span className="count">({counts.overview})</span></button>
              <button className={tab === "matched" ? "active" : ""} onClick={() => setTab("matched")}>Matched <span className="count">({counts.matched})</span></button>
              <button className={tab === "pending" ? "active" : ""} onClick={() => setTab("pending")}>Pending <span className="count">({counts.pending})</span></button>
              <button className={tab === "issues" ? "active" : ""} onClick={() => setTab("issues")}>Issues <span className="count">({counts.issues})</span></button>
            </div>
            <div className="row gap-sm">
              <div className="topbar-search" style={{minWidth: 240}}>
                <Icon name="search" size={13}/>
                <input placeholder="Search vendor or PO…" value={query} onChange={(e) => setQuery(e.target.value)} />
              </div>
              <button className="btn sm"><Icon name="filter" size={13}/> Filters</button>
            </div>
          </div>
        </div>

        <table className="tbl">
          <thead>
            <tr>
              <th style={{width: "22%"}}>Vendor</th>
              <th>Purchase Order</th>
              <th>Invoice</th>
              <th>Goods Receipt</th>
              <th>Variance</th>
              <th style={{width: 130}}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const diff = r.invAmt - r.poAmt;
              const statusMap = {
                matched: { cls: "ok", label: "Matched" },
                awaiting: { cls: "neutral", label: "Awaiting GRN" },
                variance: { cls: "warn", label: "Variance" },
                pending: { cls: "warn", label: "Pending Review" },
                issue: { cls: "crit", label: "Issue" },
              };
              const s = statusMap[r.status];
              return (
                <tr key={r.id} className="clickable" onClick={() => setSelected(r)}>
                  <td>
                    <div className="cell-stack">
                      <div className="cell-strong">{r.vendor}</div>
                      <div className="cell-sub">{r.vendorLoc} · {r.poDate}</div>
                    </div>
                  </td>
                  <td>
                    <div className="cell-stack">
                      <div className="cell-sub mono">#{r.po}</div>
                      <div className="cell-strong tabular">{fmt(r.poAmt)} <span className="muted text-xs" style={{fontWeight: 400}}>SAR</span></div>
                    </div>
                  </td>
                  <td>
                    <div className="cell-stack">
                      <div className="cell-sub mono">#{r.invoice}</div>
                      <div className="cell-strong tabular">{fmt(r.invAmt, {dp: 2})} <span className="muted text-xs" style={{fontWeight: 400}}>SAR</span></div>
                    </div>
                  </td>
                  <td>
                    {r.grn ? (
                      <div className="cell-stack">
                        <div className="cell-sub mono">#{r.grn}</div>
                        <div className="cell-strong" style={{color: "var(--ok)"}}>✓ Received</div>
                      </div>
                    ) : (
                      <div className="cell-stack">
                        <div className="cell-sub">—</div>
                        <div className="cell-sub" style={{color: "var(--muted)"}}>Pending SAP sync</div>
                      </div>
                    )}
                  </td>
                  <td>
                    {diff === 0 ? <span className="muted">—</span> : (
                      <span className="tabular" style={{color: diff > 0 ? "var(--warn)" : "var(--ok)", fontWeight: 500}}>
                        {diff > 0 ? "+" : ""}{fmt(diff, {dp: 2})}
                      </span>
                    )}
                  </td>
                  <td><span className={`pill ${s.cls}`}><span className="dot"></span>{s.label}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <MatchDrawer match={selected} onClose={() => setSelected(null)} />
    </div>
  );
}

function MatchDrawer({ match, onClose }) {
  if (!match) return <Drawer open={false} onClose={onClose}><div></div></Drawer>;
  const diff = match.invAmt - match.poAmt;
  const lineTotal = match.qty * match.rate;
  return (
    <Drawer open={!!match} onClose={onClose}>
      <div className="drawer-head">
        <div>
          <div className="drawer-title">{match.vendor}</div>
          <div className="drawer-sub mono">PO #{match.po} · {match.poDate} · {match.vendorLoc}</div>
        </div>
        <div className="drawer-actions">
          <button className="btn sm"><Icon name="plus" size={13}/> Create GRN</button>
          <button className="btn sm"><Icon name="file" size={13}/> PO View</button>
          <button className="btn sm"><Icon name="eye" size={13}/> Invoice</button>
          <button className="drawer-close" onClick={onClose}><Icon name="x" size={16}/></button>
        </div>
      </div>
      <div className="drawer-body">
        {/* Header diff bar */}
        <div className="diff-bar mb-3">
          <span className="label">PO</span><span className="val tabular">{fmt(match.poAmt)} SAR</span>
          <span className="sep">·</span>
          <span className="label">Invoice</span><span className="val tabular">{fmt(match.invAmt, {dp: 2})} SAR</span>
          <span className="sep">·</span>
          <span className="label">Difference</span>
          <span className={`val tabular ${diff > 0 ? "warn" : diff < 0 ? "crit" : "ok"}`}>{diff > 0 ? "+" : ""}{fmt(diff, {dp: 2})} SAR</span>
          <div style={{flex: 1}}></div>
          <span className={`pill ${match.status === "matched" ? "ok" : match.status === "issue" ? "crit" : "warn"}`}>
            <span className="dot"></span>{match.status === "matched" ? "Matched" : match.status === "awaiting" ? "Awaiting GRN" : match.status === "issue" ? "Issue" : "Pending"}
          </span>
        </div>

        {/* AI reasoning */}
        {match.aiNote && (
          <div className="ai-box mb-3">
            <div className="ai-icon">P</div>
            <div className="ai-body">
              <span className="ai-label">AI Reasoning</span>
              {match.aiNote}
            </div>
          </div>
        )}

        {/* Line items */}
        <div className="section">
          <div className="section-head">
            <div className="section-title">Line Item Comparison · 1 item</div>
            <div className="row gap-sm">
              <button className="chip" style={{background: "var(--ink)", color: "#fff", borderColor: "var(--ink)"}}>All (1)</button>
              <button className="chip">Pending (1)</button>
            </div>
          </div>
          <table className="tbl" style={{borderRadius: 6, border: "1px solid var(--border)"}}>
            <thead>
              <tr>
                <th>#</th>
                <th>Item</th>
                <th>UOM</th>
                <th style={{textAlign: "right"}}>PO<div className="text-xs muted" style={{fontWeight: 400, textTransform: "none", letterSpacing: 0}}>Qty / Rate</div></th>
                <th style={{textAlign: "right"}}>GRN<div className="text-xs muted" style={{fontWeight: 400, textTransform: "none", letterSpacing: 0}}>Qty</div></th>
                <th style={{textAlign: "right", background: "rgba(184, 89, 14, 0.06)"}}>Invoice<div className="text-xs muted" style={{fontWeight: 400, textTransform: "none", letterSpacing: 0}}>Qty / Rate</div></th>
                <th style={{textAlign: "right"}}>Variance</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="muted text-sm">1</td>
                <td className="cell-strong">{match.item}</td>
                <td>{match.uom}</td>
                <td className="text-right tabular">
                  <div>{match.qty}</div>
                  <div className="text-xs muted">@{fmt(match.rate)}</div>
                  <div className="text-xs">{fmt(lineTotal, {dp: 2})}</div>
                </td>
                <td className="text-right muted">—</td>
                <td className="text-right tabular" style={{background: "rgba(184, 89, 14, 0.06)"}}>
                  <div>{match.qty}</div>
                  <div className="text-xs muted">@{fmt(match.rate)}</div>
                  <div className="text-xs">{fmt(lineTotal, {dp: 2})}</div>
                </td>
                <td className="text-right tabular" style={{color: diff > 0 ? "var(--warn)" : "var(--muted)", fontWeight: 500}}>{diff > 0 ? "+" : ""}{fmt(diff, {dp: 1})}</td>
              </tr>
            </tbody>
          </table>
          <div className="row gap-md mt-2 text-xs">
            <span><span className="activity-dot ok"></span>Matched (0)</span>
            <span><span className="activity-dot warn"></span>Pending (1)</span>
          </div>
        </div>

        {/* Financial insights */}
        <div className="section">
          <div className="section-title mb-2">Financial Insights</div>
          <div className="card" style={{padding: "14px 18px"}}>
            <div className="row between">
              <div>
                <div style={{fontWeight: 500}}>Line items variance</div>
                <div className="text-sm muted">Invoice line totals exceed PO by 15% VAT</div>
              </div>
              <div className="tabular" style={{color: "var(--warn)", fontWeight: 600, fontSize: 16}}>+{fmt(diff, {dp: 1})} SAR</div>
            </div>
            <div style={{height: 1, background: "var(--border)", margin: "14px 0"}}></div>
            <div className="text-sm" style={{color: "var(--ink-2)", lineHeight: 1.6}}>
              The Purchase Order and Invoice have been received. Waiting for Goods Receipt Note (GRN) to complete the 3-way match verification.
              <div className="mt-2"><strong style={{color: "var(--ink)"}}>Action:</strong> GRN will be matched automatically once received from SAP.</div>
            </div>
          </div>
        </div>

        {/* Document totals */}
        <div className="section">
          <div className="section-title mb-2">Document Totals</div>
          <div className="card" style={{padding: "14px 18px"}}>
            <div className="row gap-lg" style={{justifyContent: "space-between"}}>
              <div>
                <div className="text-xs muted">PO</div>
                <div className="tabular" style={{fontWeight: 600, fontSize: 15}}>{fmt(match.poAmt)} <span className="muted text-xs" style={{fontWeight: 400}}>(1 item)</span></div>
              </div>
              <div>
                <div className="text-xs muted">Invoice</div>
                <div className="tabular" style={{fontWeight: 600, fontSize: 15}}>{fmt(match.invAmt, {dp: 1})} <span className="muted text-xs" style={{fontWeight: 400}}>(1 item)</span></div>
              </div>
              <div>
                <div className="text-xs muted">GRN</div>
                <div className="tabular" style={{fontWeight: 600, fontSize: 15, color: "var(--muted)"}}>— <span className="text-xs" style={{fontWeight: 400}}>(pending)</span></div>
              </div>
              <div className="row gap-sm" style={{fontSize: 13, color: "var(--muted)"}}>
                <span className="tabular" style={{color: "var(--ink)", fontWeight: 500}}>{match.qty}.00 ordered</span>
                <Icon name="arrow" size={12}/>
                <span className="tabular" style={{color: "var(--ink)", fontWeight: 500}}>0.00 received</span>
                <span className="chip">0%</span>
                <span className="text-xs">awaiting goods receipt</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Drawer>
  );
}

Object.assign(window, { InvoiceGrnAgent });
