/* ============================================================
   brandops.jsx — Brand Ops (Step 1 trigger persona)
   Master table of the brand's debit notes. Each AVAILABLE note has a
   "Generate Credit Note" button so the user picks the exact one to push
   through the pipeline; already-generated notes show their live status.
   ============================================================ */

function BrandOpsApp({ store }) {
  const { docs, businesses, bizById, generateCreditNote, fetchDebitNote, uploadDebitNote } = store;
  const [busyId, setBusyId] = React.useState(null);
  const [fetching, setFetching] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const fileRef = React.useRef(null);
  const [err, setErr] = React.useState("");
  const [range, setRange] = React.useState("all");
  const [filter, setFilter] = React.useState("all");  // all | available | done
  const [tab, setTab] = React.useState("create");

  const who = store.user || {};
  const brand = businesses[0] || bizById(who.business_id || "");
  const noApprover = brand && !brand.email;

  let rows = docs.filter((d) => withinRange(d.createdAt, range));
  if (filter === "available") rows = rows.filter((d) => d.status === "received");
  if (filter === "done") rows = rows.filter((d) => d.status !== "received");
  // available first, then most-recent
  rows = rows.slice().sort((a, b) =>
    (a.status === "received" ? 0 : 1) - (b.status === "received" ? 0 : 1) ||
    (b.createdAt || "").localeCompare(a.createdAt || ""));

  const availableCount = docs.filter((d) => d.status === "received").length;

  const doFetch = async () => {
    setErr("");
    setFetching(true);
    const res = await fetchDebitNote();
    setFetching(false);
    if (res && !res.ok)
      setErr(res.error === "no_finance_approver"
        ? "No authorised finance approver is configured for your brand yet. Contact Nakad to set it up."
        : res.error === "no_documents"
        ? "No debit notes available from the source right now."
        : "Couldn't fetch a debit note just now — please try again.");
  };

  const doUpload = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (e.target) e.target.value = "";   // allow re-selecting the same file
    if (!file) return;
    setErr(""); setUploading(true);
    const res = await uploadDebitNote(file);
    setUploading(false);
    if (res && !res.ok)
      setErr(res.error === "no_finance_approver"
        ? "No authorised finance approver is configured for your brand yet."
        : /already been uploaded/i.test(res.error || "")
          ? "This exact PDF has already been uploaded."
          : "Couldn't upload that PDF — please try again.");
  };

  const generate = async (id) => {
    setErr("");
    if (noApprover) {
      setErr("No authorised finance approver is configured for your brand yet. Contact Nakad to set it up before generating a credit note.");
      return;
    }
    setBusyId(id);
    const res = await generateCreditNote(id);
    setBusyId(null);
    if (res && !res.ok)
      setErr(res.error === "no_finance_approver"
        ? "No authorised finance approver is configured for your brand yet. Contact Nakad to set it up."
        : "Couldn't generate the credit note just now — please try again.");
  };

  return (
    <div className="app">
      <AppHeader
        store={store}
        sub="Brand Operations"
        who={{ av: (who.name || "BO").slice(0, 2).toUpperCase(), name: who.name || "Brand Ops",
               role: brand ? brand.name : "Creates credit notes" }}
      />
      <Tabs items={[{ id: "create", label: "Debit Notes", count: availableCount || null }, { id: "notif", label: "Settings" }]} active={tab} onChange={setTab} />
      <div className="main">
        {tab === "notif" ? (
          <div className="container" style={{ maxWidth: 920 }}><NotificationSettings /></div>
        ) : (
        <div className="container">
          <div className="page-head">
            <div>
              <div className="ph-title">Debit notes</div>
              <div className="ph-sub">Pick a debit note and generate its credit note — it's taken through the pipeline automatically.</div>
            </div>
            <div className="spacer" />
            <TimeFilter value={range} onChange={setRange} />
          </div>

          {err ? (
            <div className="hint mb20" style={{ background: "var(--red-bg)", borderColor: "var(--red-fg)" }}>
              <Ic.x style={{ marginTop: 1, flex: "0 0 15px", color: "var(--red-fg)" }} />
              <div style={{ color: "var(--red-fg)" }}>{err}</div>
            </div>
          ) : (
            <div className="hint info mb20">
              <Ic.bolt style={{ marginTop: 1, flex: "0 0 15px" }} />
              <div><b>{availableCount}</b> debit note{availableCount === 1 ? "" : "s"} ready to generate for {brand ? brand.name : "your brand"}. Generating moves a note to <b>Processing</b> until it's verified in Tally.</div>
            </div>
          )}

          <div className="toolbar">
            <select className="select" value={filter} onChange={(e) => setFilter(e.target.value)}>
              <option value="all">All debit notes</option>
              <option value="available">Available to generate</option>
              <option value="done">Already generated</option>
            </select>
            <div className="spacer" />
            <input ref={fileRef} type="file" accept="application/pdf,.pdf" style={{ display: "none" }} onChange={doUpload} />
            <button className="btn btn-sm" disabled={uploading || noApprover}
                    onClick={() => fileRef.current && fileRef.current.click()}
                    title="Upload a debit-note PDF from your computer">
              {uploading ? "Uploading…" : "Upload debit note (.pdf)"}
            </button>
            <button className="btn btn-primary btn-sm" disabled={fetching || noApprover}
                    onClick={doFetch} title="Pull the next debit note from the source">
              {fetching ? "Fetching…" : "Fetch debit note"}
            </button>
          </div>

          <div className="card tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Debit note</th><th>Invoice</th><th>Date</th><th>Amount</th><th style={{ width: 230 }}>Status / Action</th></tr></thead>
              <tbody>
                {rows.map((d) => {
                  const available = d.status === "received";
                  return (
                    <tr key={d.id} style={{ cursor: "default" }}>
                      <td className="doc-no mono">{d.dnNo}</td>
                      <td className="muted mono" style={{ fontSize: 13 }}>{d.invoice || "—"}</td>
                      <td className="muted" style={{ fontSize: 13 }}>{d.docDate || d.fetched}</td>
                      <td className="amt">{fmtINR(d.amount)}</td>
                      <td>
                        {available ? (
                          <button className="btn btn-primary btn-sm" disabled={busyId === d.id} onClick={() => generate(d.id)}>
                            <Ic.bolt />{busyId === d.id ? "Generating…" : "Generate Credit Note"}
                          </button>
                        ) : (
                          <StatusBadge status={d.status} ops />
                        )}
                      </td>
                    </tr>
                  );
                })}
                {!rows.length && <tr><td colSpan="5"><div className="empty" style={{ padding: "36px 0" }}><div className="e-s">No debit notes in this view.</div></div></td></tr>}
              </tbody>
            </table>
          </div>
        </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { BrandOpsApp });
