// PriceList.jsx — Account & Finance › Customer Price List
// Pick a customer (name + code) on the left, see their negotiated day-rate
// for every machine type on the right: current given price + the date it
// took effect, plus the previous price and its date.

const _fmtRM = (n) => 'RM ' + Number(n).toLocaleString('en-MY');
const _fmtPriceDate = (iso) =>
  iso ? new Date(iso + 'T00:00:00').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '—';

function PriceDelta({ current, last, changed }) {
  if (!changed || current === last) {
    return <span style={{fontSize: 11, fontWeight: 600, color: 'var(--color-grey-400)'}}>No change</span>;
  }
  const up = current > last;
  const pct = Math.round(Math.abs(current - last) / last * 100);
  const Ico = up ? window.TrendUp : window.TrendDown;
  const color = up ? '#15803d' : 'var(--color-danger)';
  return (
    <span style={{display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11.5, fontWeight: 700, color}}>
      <Ico size={12}/>{up ? '+' : '−'}{pct}%
    </span>
  );
}

function PriceListPage({ role }) {
  const canEditPrices = role === 'Admin' || role === 'Finance';
  const [selId, setSelId] = React.useState(CUSTOMERS[0].id);
  const [q, setQ] = React.useState('');

  const customer = CUSTOMERS.find(c => c.id === selId) || CUSTOMERS[0];
  const rows = React.useMemo(() => priceListFor(customer.id), [customer.id]);

  const filtered = CUSTOMERS.filter(c =>
    !q.trim() ||
    c.name.toLowerCase().includes(q.toLowerCase()) ||
    c.id.toLowerCase().includes(q.toLowerCase())
  );

  // Catalogue-wide stats for the selected customer
  const avgVsBase = (() => {
    const types = Object.fromEntries(PRICE_MACHINE_TYPES.map(t => [t.id, t.base]));
    const diffs = rows.map(r => (r.current - types[r.typeId]) / types[r.typeId]);
    const avg = diffs.reduce((a, b) => a + b, 0) / diffs.length;
    return Math.round(avg * 100);
  })();
  const lastUpdated = rows.reduce((a, r) => (r.priceDate > a ? r.priceDate : a), rows[0].priceDate);

  return (
    <div className="page">
      <div className="note-banner">
        <DollarSign size={16} style={{color: 'var(--color-navy)'}}/>
        <div>
          <strong>Customer Price List</strong> — negotiated day-rates per machine type, by customer. Each rate shows the current given price and effective date alongside the previous price. {canEditPrices ? 'You can revise prices.' : 'View-only — only Admin & Finance can revise prices.'}
        </div>
      </div>

      <div className="pricelist">
        {/* Customer picker */}
        <aside className="pricelist__customers card">
          <div className="card__header" style={{paddingBottom: 12}}>
            <div>
              <h3 className="card__title">Customers</h3>
              <div className="card__sub">{CUSTOMERS.length} accounts</div>
            </div>
          </div>
          <div style={{padding: '0 14px 12px'}}>
            <div className="topbar__search" style={{width: '100%'}}>
              <Search size={15} className="topbar__search-icon"/>
              <input placeholder="Search name or code…" value={q} onChange={e => setQ(e.target.value)} style={{width: '100%'}}/>
            </div>
          </div>
          <div className="pricelist__customer-list">
            {filtered.map(c => (
              <button key={c.id}
                className={"pricelist__customer " + (c.id === customer.id ? 'pricelist__customer--active' : '')}
                onClick={() => setSelId(c.id)}>
                <span className="pricelist__customer-name">{c.name}</span>
                <span className="pricelist__customer-code">{c.id}</span>
              </button>
            ))}
            {filtered.length === 0 ? (
              <div style={{padding: '18px 14px', fontSize: 13, color: 'var(--color-grey-400)', fontStyle: 'italic'}}>No customers match “{q}”.</div>
            ) : null}
          </div>
        </aside>

        {/* Price table for selected customer */}
        <section className="pricelist__detail card">
          <div className="card__header" style={{flexWrap: 'wrap', gap: 12}}>
            <div>
              <h3 className="card__title">{customer.name}</h3>
              <div className="card__sub">
                Customer code <span style={{fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--color-navy)'}}>{customer.id}</span> · {rows.length} machine types priced
              </div>
            </div>
            {canEditPrices
              ? <button className="btn btn--primary" onClick={() => window.askAdminPassword('Revise customer prices', () => {})}><Edit size={14}/> Revise prices</button>
              : <span className="restricted-tag"><Lock size={11}/> Admin &amp; Finance only</span>}
          </div>

          <div className="pricelist__stats">
            <div className="pricelist__stat">
              <div className="pricelist__stat-label">Avg vs. standard rate</div>
              <div className="pricelist__stat-value" style={{color: avgVsBase > 0 ? '#15803d' : avgVsBase < 0 ? 'var(--color-danger)' : 'var(--color-navy)'}}>
                {avgVsBase > 0 ? '+' : ''}{avgVsBase}%
              </div>
            </div>
            <div className="pricelist__stat">
              <div className="pricelist__stat-label">Machine types priced</div>
              <div className="pricelist__stat-value">{rows.length}</div>
            </div>
            <div className="pricelist__stat">
              <div className="pricelist__stat-label">Last price update</div>
              <div className="pricelist__stat-value">{_fmtPriceDate(lastUpdated)}</div>
            </div>
          </div>

          <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
            <table className="table pricelist__table">
              <thead>
                <tr>
                  <th>Machine Type</th>
                  <th style={{textAlign: 'right'}}>Given Price</th>
                  <th>Price Date</th>
                  <th style={{textAlign: 'right'}}>Last Price</th>
                  <th>Last Price Date</th>
                  <th style={{textAlign: 'right'}}>Change</th>
                </tr>
              </thead>
              <tbody>
                {rows.map(r => {
                  const cat = CATEGORIES.find(c => c.name === r.category);
                  return (
                    <tr key={r.typeId}>
                      <td>
                        <div style={{display: 'flex', alignItems: 'center', gap: 9}}>
                          <span style={{width: 9, height: 9, borderRadius: '50%', background: cat ? cat.color : 'var(--color-grey-400)', flexShrink: 0}}/>
                          <span>
                            <span style={{fontWeight: 600, color: 'var(--color-navy)'}}>{r.category}</span>
                            <span style={{color: 'var(--color-grey-500)', marginLeft: 6, fontFamily: 'var(--font-mono)', fontSize: 12}}>{r.spec}</span>
                          </span>
                        </div>
                      </td>
                      <td style={{textAlign: 'right', fontWeight: 700, color: 'var(--color-navy)', whiteSpace: 'nowrap'}}>{_fmtRM(r.current)}<span style={{fontWeight: 500, fontSize: 11, color: 'var(--color-grey-400)'}}> /day</span></td>
                      <td style={{whiteSpace: 'nowrap', color: 'var(--color-grey-700)'}}>{_fmtPriceDate(r.priceDate)}</td>
                      <td style={{textAlign: 'right', whiteSpace: 'nowrap', color: 'var(--color-grey-500)'}}>{r.changed ? _fmtRM(r.last) : '—'}</td>
                      <td style={{whiteSpace: 'nowrap', color: 'var(--color-grey-500)'}}>{r.changed ? _fmtPriceDate(r.lastDate) : '—'}</td>
                      <td style={{textAlign: 'right'}}><PriceDelta current={r.current} last={r.last} changed={r.changed}/></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { PriceListPage });
