// hydor-page-ops.jsx — Call Center (visit queue, appointment dispatch, ranking),
// below-price approval request + approver queue. Depends on engine + ui + forms.

const fmtT = (ts) => new Date(ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });

/* ===== below-price approval REQUEST (staff / team manager) ===== */
function ApprovalRequestForm({ onClose }) {
  const push = useToast();
  const s = Hydor.getState();
  const d = Hydor.derive();
  const me = Hydor.currentUser();
  const [f, setF] = React.useState({ productId: s.products[0] ? s.products[0].id : "", qty: 1, proposedPrice: "", partyId: "", note: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const prod = s.products.find((p) => p.id === f.productId);
  const rec = prod && d.productStats[f.productId] ? d.productStats[f.productId].recPrice : 0;
  const myCustomers = s.parties.filter((p) => p.type === "customer" && (Hydor.canU(me, "seeAllContacts") || !p.createdBy || (me && p.createdBy === me.id)));
  const submit = () => {
    if (!f.productId) return push("Pick a product.", "err");
    if (Hydor.num(f.proposedPrice, 0) <= 0) return push("Enter your proposed price.", "err");
    Hydor.submitApproval({ ...f, recPrice: rec });
    push("Approval request sent to your manager / the founder.");
    onClose();
  };
  return (
    <Modal title="Request approval — sale below recommended price" onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="unlock" onClick={submit}>Send request</Btn>
    </>}>
      <div className="form-grid">
        <Field label="Product" span2>
          <select className="sel" value={f.productId} onChange={(e) => set("productId", e.target.value)}>
            {s.products.map((p) => <option key={p.id} value={p.id}>{p.code} · {p.name}</option>)}
          </select>
        </Field>
        <Field label="Quantity"><input className="inp num" type="number" min="1" value={f.qty} onChange={(e) => set("qty", e.target.value)} /></Field>
        <Field label="Your proposed price" hint={rec ? `Recommended: ${Hydor.fmtMoney(rec)}` : ""} hintWarn>
          <Affix affix="JOD"><input className="inp num" type="number" step="0.001" value={f.proposedPrice} onChange={(e) => set("proposedPrice", e.target.value)} style={{ paddingRight: 44 }} /></Affix>
        </Field>
        <Field label="Customer" span2>
          <select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}>
            <option value="">— optional —</option>
            {myCustomers.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </Field>
        <Field label="Reason / note" span2><input className="inp" value={f.note} onChange={(e) => set("note", e.target.value)} placeholder="Why the discount is justified" /></Field>
      </div>
    </Modal>
  );
}

/* ===== approver queue — shown to owner / manager on the Transactions page ===== */
function PendingApprovals() {
  const s = useHydor();
  const push = useToast();
  const me = Hydor.currentUser();
  const role = useRole();
  if (!Hydor.can(role, "approveBelowPrice")) return null;
  const pending = s.approvals.filter((a) => a.status === "pending");
  if (!pending.length) return null;
  const uname = (id) => { const u = s.users.find((x) => x.id === id); return u ? u.name : "—"; };
  const pname = (id) => { const p = s.products.find((x) => x.id === id); return p ? p.code + " · " + p.name : "—"; };
  const cname = (id) => { const c = s.parties.find((x) => x.id === id); return c ? c.name : ""; };
  return (
    <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14, border: "1px solid var(--warn)" }}>
      <h3 className="hx-h2" style={{ marginBottom: 12, display: "flex", alignItems: "center", gap: 8 }}><Icon name="unlock" size={16} style={{ color: "var(--warn)" }} />Below-price approvals ({pending.length})</h3>
      {pending.map((a) => (
        <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border-2)" }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 500 }}>{uname(a.userId)} · {pname(a.productId)}{a.qty > 1 ? " ×" + a.qty : ""}</div>
            <div style={{ fontSize: 12, color: "var(--text-3)" }}>Proposed <b style={{ color: "var(--neg)" }}>{Hydor.fmtMoney(a.proposedPrice)}</b> vs recommended {Hydor.fmtMoney(a.recPrice)}{a.partyId ? " · " + cname(a.partyId) : ""}{a.note ? " · " + a.note : ""}</div>
          </div>
          <Btn sm variant="primary" icon="check" onClick={() => { Hydor.decideApproval(a.id, true, me && me.id); push("Approved — sale posted."); }}>Approve</Btn>
          <Btn sm variant="ghost" icon="x" onClick={() => { Hydor.decideApproval(a.id, false, me && me.id); push("Rejected."); }}>Reject</Btn>
        </div>
      ))}
    </div>
  );
}

/* ===== Call Center: visit queue, ranking, appointment dispatch ===== */
function CallCenterPage() {
  const s = useHydor();
  const push = useToast();
  const t = window.__t || ((x) => x);
  const me = Hydor.currentUser();
  const [assignFor, setAssignFor] = React.useState(null);
  const [confirmFor, setConfirmFor] = React.useState(null);
  const queue = Hydor.visitQueue();
  const uname = (id) => { const u = s.users.find((x) => x.id === id); return u ? u.name : "—"; };
  const cname = (id) => { const c = s.parties.find((x) => x.id === id); return c ? c.name : ""; };

  // appointments pending confirmation for the current field rep
  const myRole = me && me.role;
  const isFieldRep = myRole === "staff" || myRole === "teamlead";
  const pendingConfirm = isFieldRep
    ? s.appointments.filter((a) => a.assignedTo === me.id && a.status === "assigned")
    : [];

  const recentAppts = s.appointments.slice(0, 10);
  const visitEnds = s.attendance.filter((a) => a.type === "visit_end").slice(0, 12);

  return (
    <div>
      {/* FIELD REP: pending confirmation panel */}
      {pendingConfirm.length > 0 && (
        <div className="hx-panel hx-panel-pad" style={{ marginBottom: 16, borderLeft: "3px solid var(--accent)" }}>
          <h3 className="hx-h2" style={{ marginBottom: 10 }}>{t("Pending visit confirmations")} ({pendingConfirm.length})</h3>
          {pendingConfirm.map((a) => (
            <div key={a.id} style={{ display: "flex", gap: 10, alignItems: "center", padding: "10px 0", borderBottom: "1px solid var(--border-2)" }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{a.bookingCustomerName || cname(a.partyId) || "—"}</div>
                <div style={{ fontSize: 12, color: "var(--text-2)" }}>{a.bookingPhone && "📞 " + a.bookingPhone}{a.bookingAddress && " · " + a.bookingAddress}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{a.desiredAt || fmtT(a.createdAt)}{a.note ? " · " + a.note : ""}</div>
              </div>
              <Btn sm variant="primary" icon="check" onClick={() => setConfirmFor({ appt: a, defaultApproved: true })}>Confirm</Btn>
              <Btn sm variant="ghost" onClick={() => setConfirmFor({ appt: a, defaultApproved: false })}>Reject</Btn>
            </div>
          ))}
        </div>
      )}

      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--pos)" }}><div className="ms-label">{t("Free now (finished visits today)")}</div><div className="ms-value">{queue.length}</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent)" }}><div className="ms-label">{t("Appointments assigned")}</div><div className="ms-value">{s.appointments.length}</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--warn)" }}><div className="ms-label">{t("Out-of-priority")}</div><div className="ms-value">{s.appointments.filter((a) => !a.priorityOk).length}</div></div>
      </div>

      {/* priority ranking */}
      <div className="hx-panel" style={{ overflow: "hidden", marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
          <h3 className="hx-h2">{t("Visit-completion ranking — assign next appointment by priority")}</h3>
          <Btn sm variant="primary" icon="calendar" onClick={() => setAssignFor(queue[0] ? queue[0].userId : "")}>{t("Assign appointment")}</Btn>
        </div>
        {queue.length === 0 ? (
          <Empty icon="pin" title={t("No completed visits today")}>When an employee ends a visit, they appear here — ranked by who finished first.</Empty>
        ) : (
          <table className="hx-table">
            <thead><tr><th>{t("Priority")}</th><th>{t("Employee")}</th><th>{t("Finished at")}</th><th>{t("Last customer")}</th><th></th></tr></thead>
            <tbody>
              {queue.map((a, i) => (
                <tr key={a.id}>
                  <td>{i === 0 ? <Badge color="green" dot>{t("next up")}</Badge> : <span className="hx-num" style={{ color: "var(--text-3)" }}>#{i + 1}</span>}</td>
                  <td style={{ fontWeight: 500 }}>{uname(a.userId)}</td>
                  <td className="num" style={{ color: "var(--text-2)" }}>{fmtT(a.ts)}</td>
                  <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{a.partyId ? cname(a.partyId) : "—"}</td>
                  <td className="r"><Btn sm variant={i === 0 ? "primary" : "ghost"} icon="calendar" onClick={() => setAssignFor(a.userId)}>{t("Assign")}</Btn></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="cc-grid">
        {/* recent appointments */}
        <div className="hx-panel hx-panel-pad">
          <h3 className="hx-h2" style={{ marginBottom: 12 }}>{t("Recent appointments")}</h3>
          {recentAppts.length === 0 ? <p className="hx-sub">No appointments dispatched yet.</p> : recentAppts.map((a) => (
            <div key={a.id} style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "9px 0", borderBottom: "1px solid var(--border-2)" }}>
              <span className="hx-emp-badge">{uname(a.assignedTo).slice(0, 1)}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{uname(a.assignedTo)}</div>
                <div style={{ fontSize: 12.5, color: "var(--text)" }}>{a.bookingCustomerName || cname(a.partyId) || "—"}{a.bookingPhone ? " · " + a.bookingPhone : ""}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{a.bookingAddress && a.bookingAddress + " · "}{a.desiredAt || fmtT(a.createdAt)}{a.note ? " · " + a.note : ""}</div>
                {a.bookingRef && <div style={{ fontSize: 11, color: "var(--text-3)" }}>Ref: {a.bookingRef}</div>}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end", flexShrink: 0 }}>
                {a.priorityOk ? <Badge color="green">{t("in order")}</Badge> : <Badge color="red">{t("out of priority")}</Badge>}
                {a.status === "confirmed" && <Badge color="blue">✓ confirmed</Badge>}
                {a.status === "rejected" && <Badge color="gray">✗ {a.rejectReason || "rejected"}</Badge>}
              </div>
            </div>
          ))}
        </div>
        {/* visit-end feed */}
        <div className="hx-panel hx-panel-pad">
          <h3 className="hx-h2" style={{ marginBottom: 12 }}>{t("Recent visit completions")}</h3>
          {visitEnds.length === 0 ? <p className="hx-sub">No visit completions yet.</p> : visitEnds.map((a) => (
            <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 0", borderBottom: "1px solid var(--border-2)" }}>
              {a.photo ? <img src={a.photo} alt="" style={{ width: 36, height: 36, borderRadius: 8, objectFit: "cover" }} /> : <span className="hx-emp-badge">{uname(a.userId).slice(0, 1)}</span>}
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{uname(a.userId)}{a.partyId ? " · " + cname(a.partyId) : ""}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Finished {fmtT(a.ts)}{a.note ? " · " + a.note : ""}</div>
              </div>
              <Btn sm variant="ghost" icon="calendar" onClick={() => setAssignFor(a.userId)} title="Assign next appointment" />
            </div>
          ))}
        </div>
      </div>

      {assignFor !== null && <AssignAppointmentForm prefillUser={assignFor} onClose={() => setAssignFor(null)} />}
      {confirmFor !== null && <ConfirmVisitModal appt={confirmFor.appt} defaultApproved={confirmFor.defaultApproved} onClose={() => setConfirmFor(null)} />}
    </div>
  );
}

/* ===== Confirm or reject a CC-booked visit ===== */
function ConfirmVisitModal({ appt, defaultApproved, onClose }) {
  const push = useToast();
  const [approved, setApproved] = React.useState(!!defaultApproved);
  const REJECT_REASONS = ["Fake / wrong number", "Child made the appointment", "Customer cancelled", "Address not found", "Other"];
  const [reason, setReason] = React.useState("");
  const save = () => {
    if (!approved && !reason) return push("Please select a reason for rejection.", "err");
    Hydor.confirmVisit(appt.id, { approved, reason: approved ? "" : reason });
    push(approved ? "Visit confirmed — added to CC target." : "Visit rejected — call center employee notified.");
    onClose();
  };
  return (
    <Modal title={approved ? "Confirm visit" : "Reject visit"} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant={approved ? "primary" : "ghost"} icon={approved ? "check" : "x"} onClick={save}>{approved ? "Confirm visit" : "Reject visit"}</Btn>
    </>}>
      <div style={{ marginBottom: 14, padding: "12px 14px", background: "var(--bg-2)", borderRadius: 10 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 4 }}>{appt.bookingCustomerName || "Client"}</div>
        {appt.bookingPhone && <div style={{ fontSize: 12.5, color: "var(--text-2)" }}>📞 {appt.bookingPhone}</div>}
        {appt.bookingAddress && <div style={{ fontSize: 12.5, color: "var(--text-2)" }}>📍 {appt.bookingAddress}</div>}
        {appt.note && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>{appt.note}</div>}
      </div>
      <div className="hx-seg" style={{ marginBottom: 14, display: "flex", width: "100%" }}>
        <button className={approved ? "on" : ""} style={{ flex: 1 }} onClick={() => setApproved(true)}>✓ Visit was genuine</button>
        <button className={!approved ? "on" : ""} style={{ flex: 1 }} onClick={() => setApproved(false)}>✗ Not valid</button>
      </div>
      {!approved && (
        <div className="form-grid">
          <Field label="Reason for rejection" span2>
            <select className="sel" value={reason} onChange={(e) => setReason(e.target.value)}>
              <option value="">— select reason —</option>
              {REJECT_REASONS.map((r) => <option key={r} value={r}>{r}</option>)}
            </select>
          </Field>
        </div>
      )}
      {approved && <div style={{ fontSize: 12.5, color: "var(--pos)", background: "#34d3a01a", border: "1px solid var(--pos)", borderRadius: 9, padding: "8px 12px" }}>This visit will count toward the call center employee's monthly target.</div>}
    </Modal>
  );
}

/* ===== Assign appointment form ===== */
function AssignAppointmentForm({ prefillUser, onClose }) {
  const push = useToast();
  const t = window.__t || ((x) => x);
  const s = Hydor.getState();
  const queue = Hydor.visitQueue();
  const priorityUserId = queue.length ? queue[0].userId : null;
  const [useExisting, setUseExisting] = React.useState(false);
  const [f, setF] = React.useState({
    assignedTo: prefillUser || priorityUserId || "",
    partyId: "", desiredAt: "", note: "",
    bookingCustomerName: "", bookingPhone: "", bookingAddress: "", bookingRef: "",
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const reps = s.users.filter((u) => u.active && (u.department === "Sales" || u.department === "Installation & Technical" || u.role === "staff" || u.role === "teamlead"));
  const customers = s.parties.filter((p) => p.type === "customer");
  const willOverride = priorityUserId && f.assignedTo !== priorityUserId;
  const uname = (id) => { const u = s.users.find((x) => x.id === id); return u ? u.name : "—"; };
  const save = () => {
    if (!f.assignedTo) return push("Pick an employee.", "err");
    if (!useExisting && !f.bookingCustomerName) return push("Enter the customer name.", "err");
    if (!useExisting && !f.bookingPhone) return push("Enter the customer phone number.", "err");
    Hydor.assignAppointment(f);
    push(willOverride ? "Appointment assigned — founder & manager notified (out of priority)." : "Appointment assigned.");
    onClose();
  };
  return (
    <Modal title={t("Assign appointment")} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>{t("Assign")}</Btn>
    </>}>
      <div className="form-grid">
        <div className="span2">
          <div className="hx-seg" style={{ display: "flex", width: "100%", marginBottom: 4 }}>
            <button className={!useExisting ? "on" : ""} style={{ flex: 1 }} onClick={() => setUseExisting(false)}>New lead</button>
            <button className={useExisting ? "on" : ""} style={{ flex: 1 }} onClick={() => setUseExisting(true)}>Existing customer</button>
          </div>
        </div>

        {!useExisting && <>
          <Field label="Customer name" span2>
            <input className="inp" value={f.bookingCustomerName} onChange={(e) => set("bookingCustomerName", e.target.value)} placeholder="Full name" autoFocus />
          </Field>
          <Field label="Phone number">
            <input className="inp" type="tel" value={f.bookingPhone} onChange={(e) => set("bookingPhone", e.target.value)} placeholder="+962 7x xxx xxxx" />
          </Field>
          <Field label="Address / area">
            <input className="inp" value={f.bookingAddress} onChange={(e) => set("bookingAddress", e.target.value)} placeholder="Street, neighbourhood" />
          </Field>
          <Field label="Booking confirmation / ref" span2 hint="Confirmation number, source, or how they reached us">
            <input className="inp" value={f.bookingRef} onChange={(e) => set("bookingRef", e.target.value)} placeholder="e.g. Instagram DM, phone ref 1023" />
          </Field>
        </>}

        {useExisting && <Field label="Customer" span2>
          <select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}>
            <option value="">— select —</option>
            {customers.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </Field>}

        <Field label={t("Assign to")} span2 hint={priorityUserId ? "Priority: " + uname(priorityUserId) + " (finished first)" : ""}>
          <select className="sel" value={f.assignedTo} onChange={(e) => set("assignedTo", e.target.value)}>
            <option value="">— select —</option>
            {reps.map((u) => <option key={u.id} value={u.id}>{u.name}{u.id === priorityUserId ? " ★ priority" : ""}</option>)}
          </select>
        </Field>
        <Field label={t("Appointment time")}><input className="inp" type="datetime-local" value={f.desiredAt} onChange={(e) => set("desiredAt", e.target.value)} /></Field>
        <Field label="Notes"><input className="inp" value={f.note} onChange={(e) => set("note", e.target.value)} placeholder="Job details, product interest…" /></Field>

        {willOverride && (
          <div className="span2" style={{ fontSize: 12.5, color: "var(--warn)", background: "#ffc24b14", border: "1px solid #ffc24b33", borderRadius: 9, padding: "9px 12px", lineHeight: 1.5 }}>
            <Icon name="warn" size={13} style={{ verticalAlign: "middle", marginInlineEnd: 5 }} />
            Not the priority employee — founder &amp; manager will be notified.
          </div>
        )}
      </div>
    </Modal>
  );
}

Object.assign(window, { ApprovalRequestForm, PendingApprovals, CallCenterPage, AssignAppointmentForm, ConfirmVisitModal });
