function Procurement({ snapshot }) {
  const [activeTab, setActiveTab] = React.useState("stock");
  const materialOptions = React.useMemo(() => {
    const names = new Set([
      ...(snapshot.materialsStock || []).map((stock) => stock.name),
      ...(snapshot.purchaseOrders || []).map((po) => po.materialName)
    ].filter(Boolean));
    return Array.from(names);
  }, [snapshot.materialsStock, snapshot.purchaseOrders]);
  const [selectedMaterialForQuote, setSelectedMaterialForQuote] = React.useState("");

  // Material request form state
  const [requestWorkItemId, setRequestWorkItemId] = React.useState("");
  const [requestMaterial, setRequestMaterial] = React.useState("");
  const [requestQty, setRequestQty] = React.useState("");

  const ff = window.ConstructProData.formatCurrency;
  
  const stockList = snapshot.materialsStock || [];
  const pendingRequests = (snapshot.materialRequests || []).filter(r => r.status === "pending");
  const allocatedRequests = (snapshot.materialRequests || []).filter(r => r.status === "allocated");
  const purchaseOrders = snapshot.purchaseOrders || [];

  React.useEffect(() => {
    if (!selectedMaterialForQuote && materialOptions[0]) {
      setSelectedMaterialForQuote(materialOptions[0]);
    }
  }, [materialOptions, selectedMaterialForQuote]);

  React.useEffect(() => {
    if (!requestMaterial && stockList[0]?.name) {
      setRequestMaterial(stockList[0].name);
    }
  }, [stockList, requestMaterial]);

  const poHistory = selectedMaterialForQuote
    ? purchaseOrders.filter((po) => po.materialName === selectedMaterialForQuote)
    : purchaseOrders;

  const handleRaiseRequest = (e) => {
    e.preventDefault();
    if (!requestWorkItemId || !requestQty || Number(requestQty) <= 0) {
      window.ConstructProData.showToast("Please select a task and enter a valid quantity.");
      return;
    }

    window.ConstructProData.raiseMaterialRequest({
      workItemId: requestWorkItemId,
      materialName: requestMaterial,
      quantity: Number(requestQty),
      contractorName: ""
    });

    setRequestQty("");
  };

  return (
    <div className="fade-in">
      {/* Metric Cards */}
      <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-3">
        <StatCard title="Material Requests" value={pendingRequests.length} trend="Awaiting allocation" icon={<Icons.cart/>} tone={pendingRequests.length > 0 ? "warning" : "success"}/>
        <StatCard title="Total POs Issued" value={purchaseOrders.length} trend="Immutable ledger" icon={<Icons.check/>} tone="success"/>
        <StatCard title="Active Materials in Stock" value={stockList.length} trend="In-hand levels tracked" icon={<Icons.quality/>} tone="info"/>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-border-light mb-6 bg-white rounded-xl p-1 shadow-sm">
        {["stock", "requests", "bidding"].map((tab) => (
          <button
            key={tab}
            type="button"
            className={`flex-1 py-3 text-sm font-bold transition-all rounded-lg ${activeTab === tab ? "bg-primary text-white shadow" : "text-text-muted hover:text-text-primary"}`}
            onClick={() => setActiveTab(tab)}
          >
            {tab === "stock" ? "Stock Control" : tab === "requests" ? `Site Requests (${pendingRequests.length})` : "Vendor Quotation Matrix"}
          </button>
        ))}
      </div>

      {activeTab === "stock" && (
        <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.2fr_.8fr]">
          {/* Stock List table */}
          <Card>
            <SectionTitle title="Warehouse Inventory Control" subtitle="Live tracking of essential construction materials and thresholds." />
            <div className="overflow-x-auto">
              <table className="w-full min-w-[550px] text-left text-sm">
                <thead className="text-xs uppercase tracking-wider text-text-muted">
                  <tr className="border-b border-border-light">
                    <th className="py-2.5">Material</th>
                    <th>In Hand</th>
                    <th>Safety Min</th>
                    <th>Est Unit Rate</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border-light text-xs">
                  {stockList.map((stock) => {
                    const minThreshold = Number(stock.minThreshold ?? stock.reorderLevel ?? 0);
                    const unit = stock.unit || "Units";
                    const isLow = stock.inHand <= minThreshold;
                    return (
                      <tr key={stock.name} className={isLow ? "bg-warning/5 font-semibold" : ""}>
                        <td className="py-3 font-bold text-text-primary">{stock.name}</td>
                        <td className={isLow ? "text-warning font-black" : "text-text-primary"}>
                          {stock.inHand.toLocaleString()} {unit}
                        </td>
                        <td className="text-text-muted">{minThreshold.toLocaleString()} {unit}</td>
                        <td className="text-text-primary">{ff(stock.unitCost || 0)} / {unit}</td>
                        <td>
                          <Badge tone={isLow ? "warning" : "success"}>
                            {isLow ? "LOW STOCK" : "NORMAL"}
                          </Badge>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          {/* Issued POs ledger */}
          <Card>
            <SectionTitle title="Immutable Purchase Orders" subtitle="Issued work orders and material procurements." />
            <div className="space-y-3 max-h-[400px] overflow-y-auto pr-1">
              {purchaseOrders.map((po) => (
                <div key={po.id} className="rounded-xl border border-border-light bg-slate-50 p-3 space-y-1.5 text-xs shadow-sm">
                  <div className="flex items-center justify-between border-b border-border-light pb-1 font-bold">
                    <span className="text-text-primary">{po.vendorName}</span>
                    <Badge tone="success">Issued</Badge>
                  </div>
                  <div className="grid grid-cols-2 gap-1 text-[11px] text-text-muted">
                    <div>Material: <b className="text-text-primary">{po.quantity} {po.materialName}</b></div>
                    <div>Value: <b className="text-text-primary">{ff(po.quoteAmount)}</b></div>
                    <div className="col-span-2 mt-1 truncate">
                      Hash Check: <code className="text-cta font-bold text-[9px] bg-slate-100 px-1 py-0.5 rounded">{po.hash}</code>
                    </div>
                  </div>
                </div>
              ))}
              {purchaseOrders.length === 0 && (
                <p className="text-xs text-text-muted italic text-center py-6">No purchase orders dispatched yet.</p>
              )}
            </div>
          </Card>
        </div>
      )}

      {activeTab === "requests" && (
        <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.2fr_.8fr]">
          {/* Pending Material Requests */}
          <Card>
            <SectionTitle title="Contractor Material Requests" subtitle="Task-wise material request queue from field contractors." />
            <div className="space-y-3">
              <h4 className="font-bold text-xs uppercase tracking-wider text-text-muted">Pending Allocations</h4>
              {pendingRequests.map((req) => {
                const stock = stockList.find(s => s.name === req.materialName);
                const hasStock = stock ? stock.inHand >= req.quantity : false;
                return (
                  <div key={req.id} className="rounded-xl border border-border-light p-4 bg-white space-y-3">
                    <div className="flex justify-between items-start">
                      <div>
                        <h4 className="font-bold text-sm text-text-primary">{req.taskTitle}</h4>
                        <p className="text-xs text-text-muted">Requested by: {req.contractorName || "Site team"} · {(req.createdAt || "").slice(0, 10) || "—"}</p>
                      </div>
                      <Badge tone="warning">Pending</Badge>
                    </div>

                    <div className="flex justify-between items-center text-xs bg-slate-50 p-2.5 rounded-lg border border-border-light/60">
                      <div>
                        Material: <b className="text-text-primary">{req.quantity} {req.materialName}</b>
                      </div>
                      <div className={hasStock ? "text-success font-bold" : "text-danger font-bold"}>
                        Stock Level: {stock ? `${stock.inHand} ${stock.unit} available` : "No Stock!"}
                      </div>
                    </div>

                    <div className="flex justify-end gap-2">
                      {!hasStock && (
                        <Button variant="secondary" onClick={() => { setSelectedMaterialForQuote(req.materialName); setActiveTab("bidding"); }}>
                          Bidding / Quote Comparison
                        </Button>
                      )}
                      <Button onClick={() => window.ConstructProData.allocateMaterialStock(req.id)} disabled={!hasStock}>
                        Allocate Stock
                      </Button>
                    </div>
                  </div>
                );
              })}
              {pendingRequests.length === 0 && (
                <p className="text-xs text-text-muted italic text-center py-6">No pending material requests.</p>
              )}

              {allocatedRequests.length > 0 && (
                <div className="mt-6 space-y-3">
                  <h4 className="font-bold text-xs uppercase tracking-wider text-text-muted border-t border-border-light pt-4">Allocated History</h4>
                  {allocatedRequests.slice(0, 5).map((req) => (
                    <div key={req.id} className="flex items-center justify-between text-xs p-3 bg-slate-50 rounded-xl border border-border-light/40">
                      <div>
                        <span className="font-bold text-text-primary">{req.taskTitle}</span>
                        <p className="text-[10px] text-text-muted">Allocated {req.quantity} {req.materialName} to {req.contractorName}</p>
                      </div>
                      <Badge tone="success">Allocated</Badge>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </Card>

          {/* Raise Request Form */}
          <Card>
            <SectionTitle title="Raise Site Request" subtitle="Submit a future material allocation requirement for a task." />
            <form onSubmit={handleRaiseRequest} className="space-y-4">
              <label className="block">
                <span className="mb-1 block text-xs font-bold uppercase tracking-wider text-text-muted">Select Task</span>
                <select 
                  value={requestWorkItemId} 
                  onChange={(e) => setRequestWorkItemId(e.target.value)} 
                  className="w-full rounded-lg border border-border-light px-3 py-2 text-xs transition-colors focus:border-cta"
                  required
                >
                  <option value="">-- Choose active WBS task --</option>
                  {snapshot.workItems.filter(w => w.type !== "phase" && w.status !== "approved").map((w) => (
                    <option key={w.id} value={w.id}>{w.title}</option>
                  ))}
                </select>
              </label>

              <label className="block">
                <span className="mb-1 block text-xs font-bold uppercase tracking-wider text-text-muted">Material Name</span>
                <select 
                  value={requestMaterial} 
                  onChange={(e) => setRequestMaterial(e.target.value)} 
                  className="w-full rounded-lg border border-border-light px-3 py-2 text-xs transition-colors focus:border-cta"
                >
                  {stockList.map((stock) => (
                    <option key={stock.name} value={stock.name}>{stock.name} ({stock.unit})</option>
                  ))}
                </select>
              </label>

              <InputField id="req-qty" label="Required Quantity" type="number" value={requestQty} onChange={setRequestQty} required/>

              <Button className="w-full" type="submit">Raise Request</Button>
            </form>
          </Card>
        </div>
      )}

      {activeTab === "bidding" && (
        <div className="space-y-6">
          <Card>
            <div className="flex flex-wrap items-center justify-between gap-4">
              <div>
                <h3 className="font-bold text-text-primary text-sm uppercase tracking-wider">Vendor Quote History</h3>
                <p className="text-xs text-text-muted">Purchase orders issued from allocated site requests appear here.</p>
              </div>
              {materialOptions.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {materialOptions.map((mat) => (
                    <button
                      key={mat}
                      type="button"
                      className={`px-4 py-2 text-xs font-bold rounded-lg border transition-all ${selectedMaterialForQuote === mat ? "bg-primary border-primary text-white" : "bg-white border-border-light text-text-primary hover:bg-gray-50"}`}
                      onClick={() => setSelectedMaterialForQuote(mat)}
                    >
                      {mat}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </Card>

          {poHistory.length > 0 ? (
            <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
              {poHistory.map((po) => (
                <Card key={po.id}>
                  <div className="flex justify-between items-start mb-2">
                    <h4 className="font-bold text-sm text-text-primary">{po.vendorName}</h4>
                    <Badge tone="success">Issued</Badge>
                  </div>
                  <div className="space-y-2 border-t border-border-light pt-3 text-xs">
                    <div className="flex justify-between">
                      <span className="text-text-muted">Material:</span>
                      <b className="text-text-primary">{po.quantity} {po.materialName}</b>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-text-muted">PO Value:</span>
                      <b className="text-text-primary">{ff(po.quoteAmount)}</b>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          ) : (
            <Card>
              <p className="text-sm text-text-muted text-center py-10">
                No vendor quotes yet. Allocate material requests and issue purchase orders to build vendor history.
              </p>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Procurement });
