// Request Queue section — Step 02 in the updated flow.
// Sits between Connect and Set Rules.

const { useState: useStateRQ } = React;

const QUEUE_DATA = [
  { id: "SR2204805207", category: "Furniture",  requester: "Ananya Krishnan", boq: "Complete",   recommendation: "Approve",      vendor: "LML Plastics",          product: "Executive Chair",      specs: "High-back mesh, lumbar support, BIFMA certified", qty: 200, unitPrice: 4200,   total: 840000,  rule: "Total value under ₹10L threshold",               confidence: 91 },
  { id: "SR2204813201", category: "IT",          requester: "Rohan Mehta",     boq: "Complete",   recommendation: "Approve",      vendor: "TechSource India",      product: "Laptop Stands",        specs: "Adjustable height, aluminium, fits 13–17 in",    qty: 50,  unitPrice: 1800,   total: 90000,   rule: "Total value under ₹10L threshold",               confidence: 88 },
  { id: "SR2204819340", category: "Facilities",  requester: "Divya Nair",      boq: "Complete",   recommendation: "Approve",      vendor: "CoolTech HVAC",         product: "HVAC Unit",            specs: "5-ton split AC, 5-star BEE, R-32 refrigerant",   qty: 4,   unitPrice: 85000,  total: 340000,  rule: "Total value under ₹10L threshold",               confidence: 94 },
  { id: "SR2204822105", category: "IT",          requester: "Karthik Iyer",    boq: "Incomplete", recommendation: "Reject",       vendor: "Unknown",               product: "Network Switches",     specs: "24-port managed, PoE+ — pricing absent",         qty: 10,  unitPrice: 0,      total: 0,       rule: "BOQ missing pricing information",                confidence: 82 },
  { id: "SR2204830012", category: "Furniture",   requester: "Sneha Patel",     boq: "Incomplete", recommendation: "Reject",       vendor: "Unknown",               product: "Office Desks",         specs: "Standing-adjustable, 60×30 in — vendor absent",  qty: 100, unitPrice: 0,      total: 0,       rule: "BOQ missing vendor recommendation",              confidence: 79 },
  { id: "SR2204834521", category: "Facilities",  requester: "Arjun Sharma",    boq: "Incomplete", recommendation: "Reject",       vendor: "Unknown",               product: "Janitorial Supplies",  specs: "Multi-item consumables — specs incomplete",      qty: 500, unitPrice: 0,      total: 0,       rule: "BOQ incomplete — specs missing",                 confidence: 85 },
  { id: "SR2204841203", category: "IT",          requester: "Priya Venkat",    boq: "Complete",   recommendation: "Needs Review", vendor: "Softline Technologies", product: "Server Rack",          specs: "42U open-frame rack, 1000 lb rated",             qty: 2,   unitPrice: 220000, total: 440000,  rule: "Value exceeds ₹2L — human approval required",    confidence: 47 },
  { id: "SR2204849876", category: "Facilities",  requester: "Vikram Bose",     boq: "Complete",   recommendation: "Needs Review", vendor: "BuildRight Infra",      product: "Modular Partition",    specs: "Floor-to-ceiling glass partition system",        qty: 20,  unitPrice: 18000,  total: 360000,  rule: "Vendor not on approved list",                    confidence: 61 },
];

const REC_PILL = {
  "Approve":      <span className="pill pill-green"><span className="pdot"></span>Approve</span>,
  "Reject":       <span className="pill pill-red"><span className="pdot"></span>Reject</span>,
  "Needs Review": <span className="pill pill-orange"><span className="pdot"></span>Needs review</span>,
};

const BOQ_PILL = {
  "Complete":   <span className="pill pill-green"><span className="pdot"></span>Complete</span>,
  "Incomplete": <span className="pill pill-red"><span className="pdot"></span>Incomplete</span>,
};

function ConfidenceBar({ value }) {
  const tone = value >= 80 ? "var(--green)" : value >= 60 ? "var(--orange)" : "var(--red)";
  return (
    <div className="conf-bar-wrap">
      <div className="conf-bar-track">
        <div className="conf-bar-fill" style={{ width: value + "%", background: tone }}></div>
      </div>
      <span className="conf-label" style={{ color: tone }}>{value}%</span>
    </div>
  );
}

function ExpandedRow({ req, onConfirm, onReject, rejectedIds }) {
  const isRejected = rejectedIds.has(req.id);
  const formatCurrency = (n) => n > 0 ? "₹" + n.toLocaleString("en-IN") : "—";

  return (
    <tr className="expanded-row-tr">
      <td colSpan={6} className="expanded-cell">
        <div className="expanded-panel">
          <div className="expanded-grid">
            <div className="expanded-col">
              <div className="exp-label">Extracted BOQ details</div>
              <div className="kv-block" style={{ marginTop: 8 }}>
                <div className="kv-row"><span className="k">Product</span><span className="v">{req.product}</span><span></span></div>
                <div className="kv-row"><span className="k">Specs</span><span className="v">{req.specs}</span><span></span></div>
                <div className="kv-row"><span className="k">Quantity</span><span className="v">{req.qty} units</span><span></span></div>
                <div className="kv-row"><span className="k">Unit price</span><span className="v">{formatCurrency(req.unitPrice)}</span><span></span></div>
                <div className="kv-row"><span className="k">Total value</span><span className="v">{formatCurrency(req.total)}</span><span></span></div>
                <div className="kv-row"><span className="k">Vendor</span><span className="v">{req.vendor}</span><span></span></div>
              </div>
            </div>
            <div className="expanded-col">
              <div className="exp-label">Rule that fired</div>
              <div className="rule-callout rule-callout-neutral" style={{ marginTop: 8 }}>
                <div className="ic ic-neutral">R</div>
                <div className="body">
                  <div className="label">Policy match</div>
                  <div style={{ marginTop: 4 }}>{req.rule}</div>
                  <div className="expr">{req.id} · {req.category}</div>
                </div>
              </div>
              <div className="exp-label" style={{ marginTop: 14 }}>Extraction confidence</div>
              <div style={{ marginTop: 8 }}>
                <ConfidenceBar value={req.confidence} />
              </div>
            </div>
          </div>
          <div className="expanded-actions">
            {req.recommendation === "Approve" && (
              isRejected ? null :
              <button className="btn btn-confirm" onClick={() => onConfirm(req)}>
                <Icon.check size={13} /> Confirm approval
              </button>
            )}
            {req.recommendation === "Reject" && (
              isRejected
                ? <span className="inline-notice inline-notice-red">Rejection noted — requester will be notified</span>
                : <button className="btn btn-reject" onClick={() => onReject(req.id)}>
                    <Icon.x size={13} /> Confirm rejection
                  </button>
            )}
            {req.recommendation === "Needs Review" && (
              isRejected
                ? <span className="inline-notice inline-notice-red">Rejection noted — requester will be notified</span>
                : (
                  <React.Fragment>
                    <button className="btn btn-confirm" onClick={() => onConfirm(req)}>
                      <Icon.check size={13} /> Approve anyway
                    </button>
                    <button className="btn btn-reject" onClick={() => onReject(req.id)}>
                      <Icon.x size={13} /> Reject
                    </button>
                  </React.Fragment>
                )
            )}
          </div>
        </div>
      </td>
    </tr>
  );
}

function RequestQueueSection({ onConfirm }) {
  const [expandedId, setExpandedId] = useStateRQ(null);
  const [rejectedIds, setRejectedIds] = useStateRQ(new Set());

  const approved = QUEUE_DATA.filter(r => r.recommendation === "Approve").length;
  const rejected = QUEUE_DATA.filter(r => r.recommendation === "Reject").length;
  const review   = QUEUE_DATA.filter(r => r.recommendation === "Needs Review").length;

  const toggleRow = (id) => setExpandedId(prev => prev === id ? null : id);

  const handleReject = (id) => {
    setRejectedIds(prev => new Set([...prev, id]));
  };

  const handleConfirm = (req) => {
    onConfirm(req);
    setExpandedId(null);
  };

  const actionBtn = (req) => {
    if (rejectedIds.has(req.id)) {
      return <span className="inline-notice inline-notice-red-sm">Rejected</span>;
    }
    if (req.recommendation === "Approve") {
      return (
        <button className="btn btn-sm btn-confirm" onClick={(e) => { e.stopPropagation(); handleConfirm(req); }}>
          Confirm
        </button>
      );
    }
    if (req.recommendation === "Reject") {
      return (
        <button className="btn btn-sm btn-reject" onClick={(e) => { e.stopPropagation(); handleReject(req.id); }}>
          Reject
        </button>
      );
    }
    return (
      <button className="btn btn-sm btn-review" onClick={(e) => { e.stopPropagation(); toggleRow(req.id); }}>
        Review
      </button>
    );
  };

  return (
    <section className="section" data-accent="5" data-screen-label="02 Request queue">
      <div className="section-head">
        <div className="titles">
          <div className="eyebrow"><span className="dotnum"></span>Step 02 · Request queue</div>
          <h2>Vendor request inbox</h2>
          <div className="desc">Procura has processed incoming BOQs and applied your rule set. Review AI recommendations and take action — or expand a row for details.</div>
        </div>
        <div className="actions">
          <button className="btn btn-sm">
            <Icon.filter size={13} /> All categories
            <Icon.chevron size={12} />
          </button>
        </div>
      </div>

      <div className="stat-strip">
        <div className="stat">
          <div className="label"><span className="pdot"></span>Total requests</div>
          <div className="num">{QUEUE_DATA.length}</div>
          <div className="delta">In current batch</div>
        </div>
        <div className="stat" data-tone="green">
          <div className="label"><span className="pdot"></span>Auto approved</div>
          <div className="num">{approved}</div>
          <div className="delta">{Math.round((approved / QUEUE_DATA.length) * 100)}% of batch</div>
        </div>
        <div className="stat" data-tone="red">
          <div className="label"><span className="pdot"></span>Auto rejected</div>
          <div className="num">{rejected}</div>
          <div className="delta">{Math.round((rejected / QUEUE_DATA.length) * 100)}% of batch</div>
        </div>
        <div className="stat" data-tone="orange">
          <div className="label"><span className="pdot"></span>Needs review</div>
          <div className="num">{review}</div>
          <div className="delta">{Math.round((review / QUEUE_DATA.length) * 100)}% of batch</div>
        </div>
      </div>

      <div className="table-wrap" style={{ borderTop: "none" }}>
        <table className="t">
          <thead>
            <tr>
              <th style={{ width: 148, paddingLeft: 24 }}>Request ID</th>
              <th style={{ width: 110 }}>Category</th>
              <th>Requester</th>
              <th style={{ width: 130 }}>BOQ status</th>
              <th style={{ width: 150 }}>AI recommendation</th>
              <th style={{ width: 110, textAlign: "right", paddingRight: 20 }}>Action</th>
            </tr>
          </thead>
          <tbody>
            {QUEUE_DATA.map((req) => (
              <React.Fragment key={req.id}>
                <tr
                  className={`queue-row${expandedId === req.id ? " queue-row-open" : ""}`}
                  onClick={() => toggleRow(req.id)}
                >
                  <td style={{ paddingLeft: 24 }}>
                    <span className="mono req-id">{req.id}</span>
                  </td>
                  <td>
                    <span className="category-tag">{req.category}</span>
                  </td>
                  <td>
                    <span className="requester-name">{req.requester}</span>
                  </td>
                  <td>{BOQ_PILL[req.boq]}</td>
                  <td>{REC_PILL[req.recommendation]}</td>
                  <td style={{ textAlign: "right", paddingRight: 16 }} onClick={(e) => e.stopPropagation()}>
                    {actionBtn(req)}
                  </td>
                </tr>
                {expandedId === req.id && (
                  <ExpandedRow
                    req={req}
                    onConfirm={handleConfirm}
                    onReject={handleReject}
                    rejectedIds={rejectedIds}
                  />
                )}
              </React.Fragment>
            ))}
          </tbody>
        </table>
      </div>

      <div className="log-foot">
        <span>{QUEUE_DATA.length} requests processed · {rejectedIds.size} rejected this session</span>
        <span className="mono">Procura read-only · no Ariba records modified</span>
      </div>
    </section>
  );
}

Object.assign(window, { RequestQueueSection, QUEUE_DATA });
