// admin/pages/orders.jsx — orders, delivery status, courier tracking, invoices

function OrdersPage({ params, go }) {
  const admin = useAdmin();
  const [q, setQ] = React.useState('');
  const [status, setStatus] = React.useState((params && params.status) || 'all');
  const [open, setOpen] = React.useState(params && params.orderId ? params.orderId : null);
  const [selected, setSelected] = React.useState({});
  const orders = admin.getOrders();

  React.useEffect(() => {
    if (params && params.status) setStatus(params.status);
    if (params && params.orderId) setOpen(params.orderId);
  }, [params && params.status, params && params.orderId]);

  let list = orders.filter(o => {
    if (status !== 'all' && o.status !== status) return false;
    if (q) {
      const hay = (o.id + ' ' + (o.details.firstName || '') + ' ' + (o.details.lastName || '') + ' ' + (o.details.phone || '') + ' ' + (o.details.city || '')).toLowerCase();
      if (!hay.includes(q.toLowerCase())) return false;
    }
    return true;
  });

  const counts = admin.STATUSES.reduce((m, s) => { m[s] = orders.filter(o => o.status === s).length; return m; }, { all: orders.length });
  const current = open ? orders.find(o => o.id === open) : null;
  const selectedIds = Object.keys(selected).filter((id) => selected[id]);

  const bulkPack = async () => {
    if (!selectedIds.length) return;
    if (!window.confirm(`Mark ${selectedIds.length} order(s) as packed?`)) return;
    try {
      await OwnerOps.bulkUpdateOrderStatus(selectedIds, 'packed');
      setSelected({});
    } catch (e) { alert(e.message); }
  };

  return (
    <div>
      <div className="toolbar">
        <div className="search-box"><AIcon name="search" /><input className="inp" placeholder="Search order, name, phone, city…" value={q} onChange={e => setQ(e.target.value)} /></div>
        <select className="sel" style={{ width: 'auto' }} value={status} onChange={e => { setStatus(e.target.value); if (go) go('orders', e.target.value === 'all' ? {} : { status: e.target.value }); }}>
          <option value="all">All statuses ({counts.all})</option>
          {admin.STATUSES.map(s => <option key={s} value={s}>{admin.STATUS_LABEL[s]} ({counts[s] || 0})</option>)}
        </select>
        <div style={{ flex: 1 }}></div>
        {selectedIds.length > 0 && (
          <button className="btn btn-sm btn-primary" onClick={bulkPack}>Pack selected ({selectedIds.length})</button>
        )}
        <button className="btn btn-soft" onClick={() => exportOrders(list)}><AIcon name="pdf" size={15} />Export list</button>
      </div>

      <div className="card table-scroll">
        <table className="tbl">
          <thead><tr><th></th><th>Order</th><th>Customer</th><th>Items</th><th>Payment</th><th>Courier</th><th>Status</th><th className="num">Total</th><th></th></tr></thead>
          <tbody>
            {list.map(o => (
              <tr key={o.id}>
                <td><input type="checkbox" checked={!!selected[o.id]} onChange={(e) => setSelected({ ...selected, [o.id]: e.target.checked })} aria-label={'Select ' + o.id} /></td>
                <td><b>{o.id}</b><br /><span className="muted" style={{ fontSize: '.74rem' }}>{dateFmt(o.placedAt)}</span></td>
                <td>{(o.details.firstName || '') + ' ' + (o.details.lastName || '')}<br /><span className="muted" style={{ fontSize: '.74rem' }}>{o.details.city}, {o.details.state}</span></td>
                <td className="muted">{o.lines.reduce((s, l) => s + l.qty, 0)} item(s)</td>
                <td className="muted">{(o.details && o.details.payMethod) || '—'}</td>
                <td>{o.courier ? <span style={{ fontSize: '.8rem' }}>{o.courier}<br /><span className="muted" style={{ fontSize: '.72rem' }}>{o.awb}</span></span> : <span className="muted">—</span>}</td>
                <td><StatusBadge status={o.status} /></td>
                <td className="num">{money(o.total)}</td>
                <td><button className="btn btn-sm btn-soft" onClick={() => setOpen(o.id)}>Manage</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        {list.length === 0 && <Empty icon="box" title="No orders" note="Orders placed on the storefront appear here." />}
      </div>

      {/* Mobile cards */}
      <div className="mobile-cards">
        {list.map(o => (
          <div className="m-card" key={o.id} onClick={() => setOpen(o.id)}>
            <div className="spread"><b>{o.id}</b><StatusBadge status={o.status} /></div>
            <div>{(o.details.firstName || '') + ' ' + (o.details.lastName || '')}</div>
            <div className="spread muted"><span>{dateFmt(o.placedAt)}</span><span>{money(o.total)}</span></div>
          </div>
        ))}
      </div>

      {current && <OrderDetail order={current} onClose={() => setOpen(null)} />}
    </div>
  );
}

function exportOrders(list) {
  AdminPDF.tableReport('Orders Report', list.length + ' orders',
    [{ key: 'id', label: 'Order' }, { key: 'date', label: 'Date' }, { key: 'cust', label: 'Customer' }, { key: 'city', label: 'City' }, { key: 'status', label: 'Status' }, { key: 'total', label: 'Total', num: true }],
    list.map(o => ({ id: o.id, date: dateFmt(o.placedAt), cust: (o.details.firstName || '') + ' ' + (o.details.lastName || ''), city: o.details.city, status: APG.STATUS_LABEL[o.status] || o.status, total: money(o.total) })),
    { id: 'TOTAL', total: money(list.reduce((s, o) => s + o.total, 0)) }
  );
}

const NEXT_STATUS = { new: 'packed', packed: 'shipped', shipped: 'out_for_delivery', out_for_delivery: 'delivered' };
const FLOW = ['new', 'packed', 'shipped', 'out_for_delivery', 'delivered'];

function OrderDetail({ order, onClose }) {
  const admin = useAdmin();
  const [courier, setCourier] = React.useState(order.courier || '');
  const [awb, setAwb] = React.useState(order.awb || '');
  const [shipping, setShipping] = React.useState(false);
  const s = admin.getSettings();
  const d = order.details;
  const next = NEXT_STATUS[order.status];

  function advance(to) {
    if ((to === 'shipped') && (!courier || !awb)) { alert('Add courier name + AWB tracking number before marking as shipped.'); return; }
    if (to === 'cancelled' && !window.confirm('Cancel order ' + order.id + '?')) return;
    OwnerOps.updateOrderStatus(order.id, to).then(() => {
      if (courier || awb) admin.updateOrder(order.id, { courier, awb });
    }).catch((e) => alert(e.message));
  }
  function saveCourier() { admin.updateOrder(order.id, { courier, awb }); HAPStore && HAPStore.notify && HAPStore.notify('Courier saved'); }

  async function createShiprocket() {
    if (!admin.createShipment) return;
    setShipping(true);
    try {
      const res = await admin.createShipment(order.id);
      setCourier(res.courier || courier);
      setAwb(res.awb || awb);
      HAPStore && HAPStore.notify && HAPStore.notify('Shipment created · ' + (res.awb || ''));
    } catch (e) {
      alert(e.message || 'Shiprocket failed — enter AWB manually.');
    } finally {
      setShipping(false);
    }
  }

  function sendWa(statusKey) {
    const msg = admin.buildWaMessage(order, statusKey);
    admin.logWa(order, statusKey, msg, 'manual');
    window.open(admin.waLink(d.phone, msg), '_blank');
  }

  const waStage = { new: 'placed', packed: 'packed', shipped: 'shipped', out_for_delivery: 'out_for_delivery', delivered: 'delivered' }[order.status] || 'placed';

  return (
    <Modal wide title={'Order ' + order.id} onClose={onClose}
      foot={<>
        <button className="btn btn-ghost" onClick={() => AdminPDF.invoice(order)}><AIcon name="pdf" size={15} />Invoice PDF</button>
        <div style={{ flex: 1 }}></div>
        {['cancelled', 'delivered', 'returned'].indexOf(order.status) === -1 && <button className="btn btn-danger" onClick={() => admin.updateOrder(order.id, { status: 'cancelled' })}>Cancel order</button>}
        {next && <button className="btn btn-primary" onClick={() => advance(next)}><AIcon name="check" size={15} />Mark as {admin.STATUS_LABEL[next]}</button>}
      </>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 24 }} className="od-grid">
        {/* Left: items + customer */}
        <div>
          <div className="section-title">Items</div>
          <table className="tbl" style={{ marginBottom: 20 }}>
            <tbody>
              {order.lines.map(l => (
                <tr key={l.productId + l.variant}>
                  <td style={{ width: 44 }}><img className="tbl-thumb" src={l.product.image} alt="" /></td>
                  <td>{l.product.name}<br /><span className="muted" style={{ fontSize: '.74rem' }}>{l.variant} × {l.qty}</span></td>
                  <td className="num">{money(l.line)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="card-pad card" style={{ marginBottom: 16 }}>
            <div className="spread"><span className="muted">Subtotal</span><span>{money(order.subtotal)}</span></div>
            <div className="spread"><span className="muted">Shipping</span><span>{order.shipping ? money(order.shipping) : 'Free'}</span></div>
            {order.gst && <div className="spread"><span className="muted">GST ({order.gst.rate}%) {order.gst.igst ? 'IGST' : 'CGST+SGST'}</span><span>{money(order.gst.total)}</span></div>}
            <div className="spread" style={{ fontFamily: 'var(--a-serif)', fontSize: '1.3rem', marginTop: 6 }}><span>Total</span><span>{money(order.total)}</span></div>
          </div>
          <div className="section-title">Customer</div>
          <div style={{ fontSize: '.88rem', lineHeight: 1.6 }}>
            <b>{(d.firstName || '') + ' ' + (d.lastName || '')}</b><br />
            {[d.address, d.address2, d.city, d.state, d.pincode].filter(Boolean).join(', ')}<br />
            <span className="muted">{d.phone} {d.email ? '· ' + d.email : ''}</span><br />
            <span className="badge b-new" style={{ marginTop: 6 }}>{(d.payMethod || 'prepaid').toUpperCase()}</span>
          </div>
        </div>

        {/* Right: delivery + whatsapp */}
        <div>
          <div className="section-title">Delivery status</div>
          <div className="timeline" style={{ marginBottom: 18 }}>
            {FLOW.map((st) => {
              const done = FLOW.indexOf(st) <= FLOW.indexOf(order.status);
              const tl = (order.timeline || []).find(t => t.status === st);
              return (
                <div className="tl-item" key={st}>
                  <div className={'tl-dot' + (done ? '' : ' pending')}>{done ? <AIcon name="check" size={14} /> : <span style={{ width: 6, height: 6, borderRadius: 9, background: 'currentColor' }}></span>}</div>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: '.86rem', color: done ? 'var(--a-ink)' : 'var(--a-muted)' }}>{admin.STATUS_LABEL[st]}</div>
                    {tl && <div className="muted" style={{ fontSize: '.74rem' }}>{dateFmt(tl.at, true)}</div>}
                  </div>
                </div>
              );
            })}
          </div>

          <div className="section-title">Courier</div>
          <div className="field" style={{ marginBottom: 10 }}><label>Courier partner</label>
            <select className="sel" value={courier} onChange={e => setCourier(e.target.value)}>
              <option value="">Select courier…</option>
              {['DTDC', 'Delhivery', 'Blue Dart', 'India Post', 'Ekart', 'Professional Couriers', 'ST Courier', 'Local delivery'].map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div className="field" style={{ marginBottom: 10 }}><label>AWB / tracking number</label><input className="inp" value={awb} onChange={e => setAwb(e.target.value)} placeholder="e.g. DT91234567" /></div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
            <button className="btn btn-soft btn-sm" onClick={saveCourier}>Save courier details</button>
            {window.APG_CONFIG && window.APG_CONFIG.useRemote && (
              <button className="btn btn-primary btn-sm" onClick={createShiprocket} disabled={shipping}>
                <AIcon name="truck" size={14} />{shipping ? 'Creating…' : 'Create Shiprocket shipment'}
              </button>
            )}
          </div>

          <div className="section-title">WhatsApp update</div>
          <div className="card-pad" style={{ background: 'var(--a-panel-2)', borderRadius: 10, border: '1px solid var(--a-line)' }}>
            <p style={{ fontSize: '.82rem', color: 'var(--a-ink)', lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{admin.buildWaMessage(order, waStage)}</p>
            <button className="btn btn-maroon btn-sm" style={{ marginTop: 10, width: '100%' }} onClick={() => sendWa(waStage)} disabled={!d.phone}>
              <AIcon name="whatsapp" size={15} />Send to {d.phone || 'customer'}
            </button>
          </div>
          {s.whatsapp.enabled && <p className="muted" style={{ fontSize: '.72rem', marginTop: 8 }}>Auto-messages are logged when status changes. Tap above to open WhatsApp pre-filled.</p>}
        </div>
      </div>
      <style>{`@media (max-width: 760px){ .od-grid { grid-template-columns: 1fr !important; } }`}</style>
    </Modal>
  );
}
window.OrdersPage = OrdersPage;
