// ADM-PROC-28 · Responses to review (cross-requirement review queue)
// Admin Web · Procurement · P0 · 1440×900
// Every new farmer response across open/active requirements, grouped for review.
// (Relocated from ADM-PROC-20 — the addendum reassigns 20 to the Farmer master list.)
// Registered as window.Pages.reviewQueue

const Ic20 = window.Icons;
const KES20 = (n) => "KSh " + Number(n).toLocaleString("en-US");
const DT20 = window.AMDATETIME;
const D20 = window.AMDATE;

// Open/active requirements with their pending (new) farmer responses.
const REVIEW_REQS = [
  { id: "PR-2026-0184", product: "Hass", target: 28000, filled: 15400, deadline: "2026-05-19",
    responses: [
      { id: "F-2731", name: "Mary Wairimu",   region: "Murang'a", qty: 6200, rate: 92, score: 96, arrived: "2026-05-12 08:41" },
      { id: "F-2905", name: "Beatrice Nyambura", region: "Murang'a", qty: 4200, rate: 93, score: 90, arrived: "2026-05-12 09:14" },
      { id: "F-2839", name: "Joseph Mwangi",  region: "Nyeri",    qty: 2200, rate: 97, score: 78, arrived: "2026-05-12 10:02" },
    ] },
  { id: "PR-2026-0183", product: "Fuerte", target: 12000, filled: 4800, deadline: "2026-05-15",
    responses: [
      { id: "F-2776", name: "Grace Wambui",   region: "Embu",     qty: 4500, rate: 76, score: 88, arrived: "2026-05-12 07:55" },
      { id: "F-2702", name: "Lucy Akinyi",    region: "Murang'a", qty: 2900, rate: 78, score: 84, arrived: "2026-05-12 11:20" },
    ] },
  { id: "PR-2026-0180", product: "Pinkerton", target: 3500, filled: 900, deadline: "2026-05-13",
    responses: [
      { id: "F-2718", name: "Daniel Kiprono", region: "Nakuru",   qty: 1400, rate: 82, score: 81, arrived: "2026-05-12 12:06" },
    ] },
];

const PRODUCT_TONE_20 = { Hass: "avocado", Fuerte: "pulp", Pinkerton: "soil" };
const scoreTone = (s) => (s >= 90 ? "success" : s >= 80 ? "info" : "warning");

const ReviewQueue = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const [search, setSearch] = useState("");
  const [reqF, setReqF] = useState("all");
  const [sort, setSort] = useState("score");
  const [decided, setDecided] = useState({}); // responseId → "accepted" | "declined"

  const decide = (rid, name, action) => {
    setDecided(prev => ({ ...prev, [rid]: action }));
    toast({ title: action === "accepted" ? "Response accepted" : "Response declined", desc: name });
  };

  const totalPending = REVIEW_REQS.reduce((a, r) => a + r.responses.filter(x => !decided[x.id]).length, 0);

  const visibleReqs = REVIEW_REQS
    .filter(r => reqF === "all" || r.id === reqF)
    .map(r => {
      let rs = r.responses.filter(x => {
        if (!search) return true;
        const q = search.toLowerCase();
        return `${x.name} ${x.region} ${x.id}`.toLowerCase().includes(q);
      });
      rs = [...rs].sort((a, b) =>
        sort === "score" ? b.score - a.score :
        sort === "qty" ? b.qty - a.qty :
        sort === "rate" ? a.rate - b.rate :
        new Date(b.arrived) - new Date(a.arrived));
      return { ...r, rs };
    })
    .filter(r => r.rs.length > 0);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Responses to review</h1>
          <p className="page-sub">Every new farmer response across your open requirements — {totalPending} awaiting your decision.</p>
        </div>
        <div className="page-actions">
          <Button variant="outline" icon={Ic20.Download}>Export</Button>
          <Button variant="primary" icon={Ic20.ClipboardList} onClick={() => go("ADM-PROC-02.html")}>All requirements</Button>
        </div>
      </div>

      {/* Toolbar */}
      <div className="rq-toolbar">
        <div className="rq-search">
          <Ic20.Search size={15}/>
          <input placeholder="Search farmer, region, ID…" value={search} onChange={(e) => setSearch(e.target.value)}/>
        </div>
        <select className="input rq-select" value={reqF} onChange={(e) => setReqF(e.target.value)}>
          <option value="all">All requirements</option>
          {REVIEW_REQS.map(r => <option key={r.id} value={r.id}>{r.id} · {r.product}</option>)}
        </select>
        <select className="input rq-select" value={sort} onChange={(e) => setSort(e.target.value)}>
          <option value="score">Sort: Score</option>
          <option value="qty">Sort: Offered qty</option>
          <option value="rate">Sort: Rate (low→high)</option>
          <option value="arrived">Sort: Newest</option>
        </select>
      </div>

      {visibleReqs.length === 0 ? (
        <Card><div className="card-body" style={{ textAlign: "center", padding: "48px 24px" }}>
          <div style={{ fontWeight: 600, fontSize: 16 }}>Nothing to review</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>All new responses have been actioned, or none match your filters.</div>
        </div></Card>
      ) : visibleReqs.map(r => {
        const pct = Math.round((r.filled / r.target) * 100);
        return (
          <Card key={r.id} className="rq-group">
            <div className="rq-group-head">
              <div className="row" style={{ gap: 10, alignItems: "center", minWidth: 0 }}>
                <span className="mono" style={{ fontWeight: 600, fontSize: 13.5 }}>{r.id}</span>
                <Badge tone={PRODUCT_TONE_20[r.product] || "outline"}>{r.product}</Badge>
                <span className="muted" style={{ fontSize: 12.5 }}>{r.filled.toLocaleString("en-US")} / {r.target.toLocaleString("en-US")} kg · {pct}% filled</span>
              </div>
              <div className="row" style={{ gap: 12, alignItems: "center" }}>
                <span className="muted" style={{ fontSize: 12 }}>Deadline {D20(r.deadline)}</span>
                <Button size="sm" variant="ghost" icon={Ic20.ArrowRight} onClick={() => go("ADM-PROC-10.html")}>Open requirement</Button>
              </div>
            </div>
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Farmer</th><th>Region</th><th className="num">Offered</th><th className="num">Rate</th>
                    <th className="num">Score</th><th>Arrived</th><th className="actions"></th>
                  </tr>
                </thead>
                <tbody>
                  {r.rs.map(x => {
                    const state = decided[x.id];
                    return (
                      <tr key={x.id} className="proc-row">
                        <td>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
                            <Avatar initials={x.name.split(" ").map(w => w[0]).join("").slice(0, 2)} size="sm"/>
                            <span><span style={{ fontWeight: 600, fontSize: 13 }}>{x.name}</span>
                              <span className="muted mono" style={{ display: "block", fontSize: 11 }}>{x.id}</span></span>
                          </span>
                        </td>
                        <td>{x.region}</td>
                        <td className="num" style={{ fontWeight: 600 }}>{x.qty.toLocaleString("en-US")}<span className="muted" style={{ fontWeight: 400 }}> kg</span></td>
                        <td className="num">{KES20(x.rate)}</td>
                        <td className="num"><Badge tone={scoreTone(x.score)}>{x.score}</Badge></td>
                        <td className="mono muted" style={{ fontSize: 12 }}>{DT20(x.arrived)}</td>
                        <td className="actions">
                          {state ? (
                            <Badge tone={state === "accepted" ? "success" : "outline"}>{state === "accepted" ? "Accepted" : "Declined"}</Badge>
                          ) : (
                            <span style={{ display: "inline-flex", gap: 6, justifyContent: "flex-end" }}>
                              <button className="btn btn-ghost btn-xs" onClick={(e) => { e.stopPropagation(); decide(x.id, x.name, "declined"); }}>Decline</button>
                              <button className="btn btn-primary btn-xs" onClick={(e) => { e.stopPropagation(); decide(x.id, x.name, "accepted"); }}>Accept</button>
                            </span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        );
      })}
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { reviewQueue: ReviewQueue });
