/* NGIPL PLM — Quotation builder */
const { useState, useEffect, useMemo, useRef } = React;

function QuotesView({ nav, toast, activeId, onActive, headerStyle }) {
  const state = PLM.useStore();
  const quote = activeId ? PLM.quoteById(activeId) : null;
  const [preview, setPreview] = useState(false);

  useEffect(() => { if (activeId && !PLM.quoteById(activeId)) onActive(null); }, [activeId, state.quotes.length]);

  if (!quote) {
    return <QuoteList onOpen={(id) => { onActive(id); setPreview(false); }} toast={toast}></QuoteList>;
  }
  if (preview) {
    return <QuotePreview quote={quote} headerStyle={headerStyle} onBack={() => setPreview(false)}></QuotePreview>;
  }
  return <QuoteEditor quote={quote} nav={nav} toast={toast}
    onBack={() => onActive(null)} onPreview={() => setPreview(true)}></QuoteEditor>;
}

/* ---------- Saved quotes ---------- */
function QuoteList({ onOpen, toast }) {
  const state = PLM.useStore();
  const [confirmDel, setConfirmDel] = useState(null);
  return (
    <div data-screen-label="Quotations">
      <div className="toolbar">
        <span className="overline" style={{ fontSize: 11, color: "var(--text-muted)" }}>{state.quotes.length} quotation{state.quotes.length === 1 ? "" : "s"}</span>
        <span className="caption">Refs never reuse · counter resets each year</span>
        <div className="spacer"></div>
        <Btn size="sm" onClick={() => { const q = PLM.addQuote(); onOpen(q.id); }}><IPlus size={13}></IPlus> New quotation</Btn>
      </div>
      <div className="panel panel--strong">
        <table className="plm-table">
          <thead>
            <tr>
              <th>Customer</th>
              <th style={{ width: 110 }}>Ref</th>
              <th style={{ width: 200 }}>Rates based on</th>
              <th className="num" style={{ width: 70 }}>Items</th>
              <th style={{ width: 150 }}>Date</th>
              <th style={{ width: 210 }}></th>
            </tr>
          </thead>
          <tbody>
            {state.quotes.map((q) => {
              const basisName = q.basis === "general" ? "General price list" : (PLM.partyById(q.basis) ? PLM.partyById(q.basis).name : "General price list");
              return (
                <tr key={q.id} className="item-row">
                  <td style={{ fontWeight: 600, cursor: "pointer" }} onClick={() => onOpen(q.id)}>{q.customer || <span style={{ color: "var(--text-faint)", fontWeight: 400 }}>Untitled customer</span>}</td>
                  <td className="tnum">{q.ref}</td>
                  <td>{basisName}</td>
                  <td className="num tnum">{q.items.length}</td>
                  <td className="caption">{q.date}</td>
                  <td>
                    <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>
                      <button type="button" className="fchip" onClick={() => onOpen(q.id)}>Open</button>
                      <button type="button" className="fchip" onClick={() => { const c = PLM.duplicateQuote(q.id); if (c) onOpen(c.id); }}>Duplicate</button>
                      {confirmDel === q.id ? (
                        <button type="button" className="fchip" style={{ borderColor: "var(--red-700)", color: "var(--red-700)" }}
                          onClick={() => { PLM.deleteQuote(q.id); toast("Deleted " + q.ref); setConfirmDel(null); }}>Confirm delete</button>
                      ) : (
                        <IconBtn title="Delete quotation" onClick={() => setConfirmDel(q.id)}><ITrash size={14}></ITrash></IconBtn>
                      )}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {!state.quotes.length ? (
          <div style={{ padding: 48, textAlign: "center" }}>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 6 }}>No quotations yet</div>
            <div className="caption" style={{ maxWidth: 420, margin: "0 auto 16px" }}>
              Pick items from the master list, load them at default rates, adjust where negotiated, then print a branded A4 quotation.
            </div>
            <Btn size="sm" onClick={() => { const q = PLM.addQuote(); onOpen(q.id); }}><IPlus size={13}></IPlus> New quotation</Btn>
          </div>
        ) : null}
      </div>
    </div>
  );
}

/* ---------- Editor ---------- */
function QuoteEditor({ quote, nav, toast, onBack, onPreview }) {
  const state = PLM.useStore();
  const [search, setSearch] = useState("");
  const [catFilter, setCatFilter] = useState("all");
  const grouped = PLM.groupedProducts();
  const nums = PLM.numberMap();
  const inQuote = new Set(quote.items.map((it) => it.productId));
  const q = search.trim().toLowerCase();

  const bands = grouped
    .filter((b) => catFilter === "all" || b.cat.id === catFilter)
    .map((b) => ({
      cat: b.cat,
      items: b.groups.reduce((a, g) => a.concat(g.items), []).filter((p) => !q || p.name.toLowerCase().includes(q)),
    }))
    .filter((b) => b.items.length);

  return (
    <div data-screen-label="Quotation Builder">
      <div className="toolbar">
        <Btn variant="ghost" size="sm" onClick={onBack}>All quotations</Btn>
        <span className="chip chip--ghost tnum">{quote.ref}</span>
        <span className="caption" title={"Last saved " + PLM.fmtDate(quote.updatedAt)}>Auto-saved {PLM.fmtDate(quote.updatedAt)}</span>
        <div className="spacer"></div>
        <Btn variant="secondary" size="sm" disabled={!quote.items.length}
          title="Save these rates as this customer's standing special rates"
          onClick={() => {
            const pa = PLM.convertQuoteToParty(quote.id);
            if (pa) { toast("Party rates created: " + pa.name); nav.goParty(pa.id); }
          }}>Save as party rates</Btn>
        <Btn variant="secondary" size="sm" onClick={() => { toast("Quotation " + quote.ref + " saved"); onBack(); }}>Save &amp; close</Btn>
        <Btn size="sm" disabled={!quote.items.length} onClick={onPreview}><IPrinter size={13}></IPrinter> Preview &amp; print</Btn>
      </div>

      <div className="panel panel--strong" style={{ marginBottom: 16, padding: "14px 16px" }}>
        <div className="f-row">
          <Field label="Customer" style={{ flex: 2 }}>
            <input className="f-input" placeholder="e.g. Taj Resort & Convention Centre"
              value={quote.customer} onChange={(e) => PLM.updateQuote(quote.id, { customer: e.target.value })} />
          </Field>
          <Field label="Load default rates from">
            <select className="f-select" value={quote.basis} onChange={(e) => { PLM.quoteSetBasis(quote.id, e.target.value); toast("Default rates loaded from " + (e.target.value === "general" ? "the general price list" : PLM.partyById(e.target.value).name)); }}>
              <option value="general">General price list</option>
              {state.parties.map((pa) => <option key={pa.id} value={pa.id}>{pa.name}</option>)}
            </select>
          </Field>
          <Field label="Billing entity">
            <select className="f-select" value={quote.entityId} onChange={(e) => PLM.updateQuote(quote.id, { entityId: e.target.value })}>
              {state.entities.map((en) => <option key={en.id} value={en.id}>{en.short}</option>)}
            </select>
          </Field>
          <Field label="Validity note (printed)" style={{ flex: 2 }}>
            <input className="f-input" value={quote.note} onChange={(e) => PLM.updateQuote(quote.id, { note: e.target.value })} />
          </Field>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "5fr 6fr", gap: 16, alignItems: "start" }}>
        <div>
          <div className="toolbar" style={{ marginBottom: 10 }}>
            <span className="overline" style={{ fontSize: 11, color: "var(--text-muted)" }}>Pick items</span>
            <div className="spacer"></div>
            <div className="search-box">
              <ISearch size={14}></ISearch>
              <input className="f-input" style={{ width: 180, height: 34, fontSize: 13 }} placeholder="Search…" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <select className="f-select" style={{ width: 150, height: 34, fontSize: 12 }} value={catFilter} onChange={(e) => setCatFilter(e.target.value)}>
              <option value="all">All categories</option>
              {state.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div className="panel plm-table-wrap" style={{ maxHeight: "calc(100vh - 350px)", minHeight: 280 }}>
            <table className="plm-table">
              <tbody>
                {bands.map((band) => (
                  <React.Fragment key={band.cat.id}>
                    <tr className="cat-band"><td colSpan={4}><span className="band-cell"><CatIcon catId={band.cat.id} size={18}></CatIcon><span>{band.cat.name}</span></span></td></tr>
                    {band.items.map((p) => {
                      const b = PLM.basisRateFor(quote.basis, p.id);
                      const on = inQuote.has(p.id);
                      return (
                        <tr key={p.id} className="item-row" style={{ cursor: "pointer" }} onClick={() => PLM.quoteToggleItem(quote.id, p.id)}>
                          <td style={{ width: 34 }}><input type="checkbox" checked={on} readOnly style={{ accentColor: "#000000" }} /></td>
                          <td className="col-no">{nums[p.id]}</td>
                          <td>{p.name}</td>
                          <td className="num tnum" style={{ width: 84 }}>₹{PLM.fmtRate(b.rate)}</td>
                        </tr>
                      );
                    })}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
            {!bands.length ? <div className="caption" style={{ padding: 16 }}>No items match.</div> : null}
          </div>
        </div>

        <div>
          <div className="toolbar" style={{ marginBottom: 10 }}>
            <span className="overline" style={{ fontSize: 11, color: "var(--text-muted)" }}>
              Quotation — {quote.items.length} item{quote.items.length === 1 ? "" : "s"}
            </span>
            <div className="spacer"></div>
            {quote.items.some((it) => it.edited) ? (
              <span className="caption">{quote.items.filter((it) => it.edited).length} rate{quote.items.filter((it) => it.edited).length === 1 ? "" : "s"} edited from default</span>
            ) : null}
          </div>
          <div className="panel panel--strong plm-table-wrap" style={{ maxHeight: "calc(100vh - 350px)", minHeight: 280 }}>
            <table className="plm-table">
              <thead>
                <tr>
                  <th className="col-no">#</th>
                  <th>Item</th>
                  <th className="num" style={{ width: 92 }}>Quoted ₹</th>
                  <th className="num" style={{ width: 84 }}>Default</th>
                  <th className="num" style={{ width: 56 }}>GST</th>
                  <th style={{ width: 44 }}></th>
                </tr>
              </thead>
              <tbody>
                <QuoteItemRows quote={quote} toast={toast}></QuoteItemRows>
              </tbody>
            </table>
            {!quote.items.length ? (
              <div className="caption" style={{ padding: 24, textAlign: "center" }}>
                Tick items on the left — they load here at the default rate, ready to adjust.
              </div>
            ) : null}
          </div>
        </div>
      </div>
    </div>
  );
}

function QuoteItemRows({ quote, toast }) {
  const pb = PLM.productsById();
  const cats = PLM.get().categories;
  const order = {};
  const nm = PLM.numberMap();
  quote.items.forEach((it) => { order[it.id] = it.productId && nm[it.productId] ? nm[it.productId] : 9999; });
  const sorted = quote.items.slice().sort((a, b) => order[a.id] - order[b.id]);
  const byCat = {};
  sorted.forEach((it) => {
    const p = pb[it.productId];
    const catId = p ? p.categoryId : "cat-other";
    (byCat[catId] = byCat[catId] || []).push(it);
  });
  let no = 0;
  const out = [];
  cats.forEach((c) => {
    if (!byCat[c.id]) return;
    out.push(<tr className="cat-band" key={"cb" + c.id}><td colSpan={6}><span className="band-cell"><CatIcon catId={c.id} size={18}></CatIcon><span>{c.name}</span></span></td></tr>);
    byCat[c.id].forEach((it) => {
      const p = pb[it.productId];
      no++;
      out.push(
        <tr className="item-row" key={it.id}>
          <td className="col-no">{no}</td>
          <td>{p ? p.name : "—"}</td>
          <td className="num rate">
            <RateCell value={it.rate} onCommit={(r) => PLM.quoteSetRate(quote.id, it.id, r)}></RateCell>
          </td>
          <td className="num tnum" style={{ color: "var(--text-faint)" }}>
            {it.edited ? "₹" + PLM.fmtRate(it.defaultRate) : "="}
          </td>
          <td className="num">{PLM.fmtGst(it.gst)}</td>
          <td>
            <span className="row-actions">
              <IconBtn title="Remove from quotation" onClick={() => PLM.quoteToggleItem(quote.id, it.productId)}><IX size={14}></IX></IconBtn>
            </span>
          </td>
        </tr>
      );
    });
  });
  return <React.Fragment>{out}</React.Fragment>;
}

/* ---------- Preview & print ---------- */
function QuotePreview({ quote, onBack, headerStyle }) {
  const state = PLM.useStore();
  const entity = PLM.entityById(quote.entityId);
  return (
    <div data-screen-label="Quotation Preview">
      <div className="toolbar print-controls">
        <Btn variant="ghost" size="sm" onClick={onBack}>Back to editor</Btn>
        <span className="caption">{quote.ref}{quote.customer ? " · " + quote.customer : ""}</span>
        <div className="spacer"></div>
        <Btn size="sm" onClick={() => {
          PLM.logPrint("Printed quotation " + quote.ref + (quote.customer ? " — " + quote.customer : "") + " (" + quote.items.length + " items)");
          window.print();
        }}><IPrinter size={13}></IPrinter> Print / Save PDF</Btn>
      </div>
      <div className="sheet-canvas">
        <PriceSheet quote={quote} entity={entity} headerStyle={headerStyle || "charcoal"}></PriceSheet>
      </div>
    </div>
  );
}

Object.assign(window, { QuotesView });
