// ADM-PROC-15 · Reschedule request review (AMOMS Module 1)
// Admin Web · Procurement Manager · P1 · 1440×900
// Components: C-108 Modal · C-014 Status pill · C-008 Time-slot picker · C-001 Button · C-106 Inline error
// Registered as window.Pages.reschedule

const Ic15 = window.Icons;
const RES_15 = {
  po: "PO-2026-0041", order: "SO-2026-0181", farmer: "Mary Wairimu", farmerId: "F-2731",
  qty: 6200, product: "Hass",
  original: { date: "Thu 15 May 2026", window: "09:00 – 11:00", short: "15 May" },
  requested: { date: "Fri 16 May 2026", window: "14:00 – 16:00", short: "16 May" },
  reason: "Heavy rain expected Thursday — roads from Kangema will be impassable for the loaded truck. Friday afternoon gives the harvest time to dry and the road to clear.",
};

const Reschedule = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.rescheduleState) || "noconflict";

  const [decision, setDecision] = useState("approve");
  const [comment, setComment] = useState("");
  const [counterDate, setCounterDate] = useState("2026-05-17");
  const [counterWindow, setCounterWindow] = useState("09:00 – 11:00");
  useEffect(() => { setDecision(state === "reject" ? "reject" : state === "counter" ? "counter" : "approve"); setComment(""); }, [state]);

  const hasConflict = state === "conflict";
  const needComment = decision === "reject";
  const canConfirm = !(needComment && !comment.trim());

  const confirm = () => {
    if (!canConfirm) { toast({ title: "Add a comment for the farmer", desc: "Required when rejecting.", tone: "danger" }); return; }
    const msg = decision === "approve" ? "Reschedule approved" : decision === "reject" ? "Reschedule rejected" : "Counter-proposal sent";
    toast({ title: msg, desc: `${RES_15.farmer} notified` });
    go("ADM-PROC-16.html");
  };

  const SlotCard = ({ tag, slot, requested }) => (
    <div className={`rr-slot${requested ? " requested" : ""}`}>
      <div className="rr-slot-tag">{tag}</div>
      <div className="rr-slot-date">{slot.date}</div>
      <div className="rr-slot-row"><Ic15.Clock size={13} />{slot.window}</div>
      <div className="rr-slot-row"><Ic15.Box size={13} />{RES_15.qty.toLocaleString("en-US")} kg {RES_15.product}</div>
      {requested && hasConflict && <div className="rr-slot-row" style={{ color: "var(--soil-fg)", fontWeight: 600 }}><Ic15.Warning size={13} />Conflicts with 2 other deliveries</div>}
    </div>
  );

  return (
    <div className="page rr-page">
      <div className="rr-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-16.html")}><Ic15.ChevronLeft size={18} /></button>
        <div style={{ flex: 1 }}>
          <h1 className="rr-title">Reschedule request — <span className="mono" style={{ fontWeight: 600 }}>{RES_15.po}</span></h1>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{RES_15.farmer} · {RES_15.order}</div>
        </div>
        <StatusBadge status="pending" />
      </div>

      {/* Slot comparison */}
      <div className="rr-slots">
        <SlotCard tag="Original slot" slot={RES_15.original} />
        <span className="rr-arrow"><Ic15.ArrowRight size={16} /></span>
        <SlotCard tag="Requested slot" slot={RES_15.requested} requested />
      </div>

      {hasConflict && (
        <div className="alert alert-warning" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic15.Warning size={16} /></span>
          <div className="alert-body"><div className="alert-title">Requested slot has a capacity conflict</div><div className="alert-desc">Fri 16 May 14:00–16:00 already has 2 confirmed deliveries (14,300 kg). You can override, but the gate may be congested.</div></div>
        </div>
      )}

      {/* Farmer reason */}
      <Card style={{ marginBottom: 16 }}>
        <CardHead title="Reason from farmer" />
        <div className="card-body" style={{ paddingTop: 2 }}>
          <div style={{ display: "flex", gap: 12 }}>
            <Avatar initials="MW" size="sm" />
            <div style={{ flex: 1, fontSize: 13.5, lineHeight: 1.55 }}>{RES_15.reason}</div>
          </div>
        </div>
      </Card>

      {/* Decision */}
      <Card>
        <CardHead title="Your decision" desc="The farmer is notified once you confirm." />
        <div className="card-body" style={{ paddingTop: 2 }}>
          <div className="rr-decide-row">
            <button className={`rr-decide approve${decision === "approve" ? " on" : ""}`} onClick={() => setDecision("approve")}>
              <Ic15.CheckCircle size={20} /><span className="rr-decide-label">Approve</span>
            </button>
            <button className={`rr-decide reject${decision === "reject" ? " on" : ""}`} onClick={() => setDecision("reject")}>
              <Ic15.XCircle size={20} /><span className="rr-decide-label">Reject</span>
            </button>
            <button className={`rr-decide counter${decision === "counter" ? " on" : ""}`} onClick={() => setDecision("counter")}>
              <Ic15.Calendar size={20} /><span className="rr-decide-label">Counter-propose</span>
            </button>
          </div>

          {decision === "counter" && (
            <div className="grid-2" style={{ gap: 16, marginTop: 16 }}>
              <div className="field"><label className="label">Proposed date</label><input type="date" className="input" value={counterDate} onChange={(e) => setCounterDate(e.target.value)} /></div>
              <div className="field"><label className="label">Time window</label>
                <select className="select" value={counterWindow} onChange={(e) => setCounterWindow(e.target.value)}>
                  <option>09:00 – 11:00</option><option>11:00 – 13:00</option><option>14:00 – 16:00</option><option>16:00 – 18:00</option>
                </select>
              </div>
            </div>
          )}

          <div className="field" style={{ marginTop: 16 }}>
            <label className="label">Comment to farmer {needComment && <span className="req">*</span>}{!needComment && <span className="muted" style={{ fontWeight: 400 }}>(optional)</span>}</label>
            <textarea className="textarea" placeholder={needComment ? "Explain why the request can't be accommodated…" : decision === "counter" ? "Suggest the new slot and why…" : "Optional note — e.g. confirmed, see you Friday."} value={comment} onChange={(e) => setComment(e.target.value)} />
            {decision === "counter" && <div className="field-hint">A counter-proposal still needs the farmer's acknowledgment to commit.</div>}
          </div>

          <div className="row" style={{ justifyContent: "flex-end", marginTop: 18 }}>
            <Button variant="outline" onClick={() => go("ADM-PROC-16.html")}>Cancel</Button>
            <Button variant="primary" icon={Ic15.Check} onClick={confirm}>Confirm decision</Button>
          </div>
        </div>
      </Card>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { reschedule: Reschedule });
