// admin/pages/crm.jsx — customer relationship management

function CrmPage() {
  const admin = useAdmin();
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(null);
  const customers = admin.getCustomers();
  const orders = admin.getOrders();

  let list = customers.filter(c => !q || (c.name + ' ' + c.phone + ' ' + c.email + ' ' + c.city).toLowerCase().includes(q.toLowerCase()));
  list = list.sort((a, b) => (b.lastOrderAt || b.createdAt) - (a.lastOrderAt || a.createdAt));

  const totalSpent = customers.reduce((s, c) => s + (c.spent || 0), 0);
  const repeat = customers.filter(c => c.orders > 1).length;

  return (
    <div>
      <div className="kpi-grid" style={{ marginBottom: 22 }}>
        <div className="kpi"><div className="kpi__label"><AIcon name="users" />Customers</div><div className="kpi__value">{customers.length}</div></div>
        <div className="kpi"><div className="kpi__label"><AIcon name="star" />Repeat buyers</div><div className="kpi__value">{repeat}</div></div>
        <div className="kpi"><div className="kpi__label"><AIcon name="rupee" />Lifetime value</div><div className="kpi__value">{money(totalSpent)}</div></div>
        <div className="kpi"><div className="kpi__label"><AIcon name="box" />Avg order</div><div className="kpi__value">{money(orders.length ? orders.reduce((s, o) => s + o.total, 0) / orders.length : 0)}</div></div>
      </div>

      <div className="toolbar">
        <div className="search-box"><AIcon name="search" /><input className="inp" placeholder="Search name, phone, email…" value={q} onChange={e => setQ(e.target.value)} /></div>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-soft" onClick={() => AdminPDF.tableReport('Customer List', customers.length + ' customers',
          [{ key: 'name', label: 'Name' }, { key: 'phone', label: 'Phone' }, { key: 'city', label: 'City' }, { key: 'orders', label: 'Orders', num: true }, { key: 'spent', label: 'Spent', num: true }],
          list.map(c => ({ name: c.name, phone: c.phone, city: c.city, orders: c.orders, spent: money(c.spent) })))}><AIcon name="pdf" size={15} />Export PDF</button>
      </div>

      <div className="card">
        <table className="tbl">
          <thead><tr><th>Customer</th><th>Contact</th><th>Location</th><th className="num">Orders</th><th className="num">Spent</th><th>Tags</th><th></th></tr></thead>
          <tbody>
            {list.map(c => (
              <tr key={c.id}>
                <td><b>{c.name}</b><br /><span className="muted" style={{ fontSize: '.74rem' }}>since {dateFmt(c.createdAt)}</span></td>
                <td style={{ fontSize: '.82rem' }}>{c.phone}<br /><span className="muted">{c.email}</span></td>
                <td className="muted" style={{ fontSize: '.82rem' }}>{c.city}{c.state ? ', ' + c.state : ''}</td>
                <td className="num">{c.orders}</td>
                <td className="num">{money(c.spent)}</td>
                <td>{(c.tags || []).map(t => <span key={t} className="badge b-new" style={{ marginRight: 4 }}>{t}</span>)}{c.orders > 1 && <span className="badge b-delivered">Repeat</span>}</td>
                <td>
                  <div className="row" style={{ justifyContent: 'flex-end' }}>
                    {c.phone && <a className="btn btn-icon btn-ghost btn-sm" title="WhatsApp" target="_blank" rel="noreferrer" href={admin.waLink(c.phone, admin.fillTemplate(admin.getSettings().whatsapp.templates.promo, { name: c.name.split(' ')[0] }))}><AIcon name="whatsapp" size={15} /></a>}
                    <button className="btn btn-sm btn-soft" onClick={() => setOpen(c)}>Open</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {list.length === 0 && <Empty icon="users" title="No customers yet" note="Customer records are created automatically when orders are placed." />}
      </div>

      {open && <CustomerDetail customer={open} onClose={() => setOpen(null)} />}
    </div>
  );
}

function CustomerDetail({ customer, onClose }) {
  const admin = useAdmin();
  const [notes, setNotes] = React.useState(customer.notes || '');
  const [tags, setTags] = React.useState((customer.tags || []).join(', '));
  const orders = admin.getOrders().filter(o => {
    const k = (o.details.phone || o.details.email || '').toLowerCase();
    return k === customer.key;
  });

  function save() {
    admin.updateCustomer(customer.id, { notes, tags: tags.split(',').map(t => t.trim()).filter(Boolean) });
    onClose();
  }

  return (
    <Modal title={customer.name} onClose={onClose}
      foot={<><button className="btn btn-ghost" onClick={onClose}>Close</button><button className="btn btn-primary" onClick={save}>Save</button></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 18 }}>
        <div className="card-pad" style={{ background: 'var(--a-panel-2)', borderRadius: 10 }}>
          <div className="section-title" style={{ margin: 0 }}>Contact</div>
          <div style={{ fontSize: '.88rem', lineHeight: 1.7, marginTop: 8 }}>
            <div>{customer.phone}</div><div className="muted">{customer.email}</div>
            <div className="muted">{customer.address}</div>
          </div>
          {customer.phone && <a className="btn btn-maroon btn-sm" style={{ marginTop: 10 }} target="_blank" rel="noreferrer" href={admin.waLink(customer.phone, 'Hi ' + customer.name.split(' ')[0] + '! ')}><AIcon name="whatsapp" size={14} />WhatsApp</a>}
        </div>
        <div className="card-pad" style={{ background: 'var(--a-panel-2)', borderRadius: 10 }}>
          <div className="section-title" style={{ margin: 0 }}>Summary</div>
          <div className="spread" style={{ marginTop: 10 }}><span className="muted">Orders</span><b>{customer.orders}</b></div>
          <div className="spread"><span className="muted">Lifetime spend</span><b>{money(customer.spent)}</b></div>
          <div className="spread"><span className="muted">Last order</span><span>{customer.lastOrderAt ? dateFmt(customer.lastOrderAt) : '—'}</span></div>
        </div>
      </div>
      <div className="form-grid">
        <div className="field span2"><label>Tags (comma-separated)</label><input className="inp" value={tags} onChange={e => setTags(e.target.value)} placeholder="VIP, wholesale, bulk" /></div>
        <div className="field span2"><label>Notes</label><textarea className="ta" value={notes} onChange={e => setNotes(e.target.value)} placeholder="Preferences, conversations, follow-ups…" /></div>
      </div>
      <div className="section-title" style={{ marginTop: 18 }}>Order history</div>
      <table className="tbl">
        <tbody>
          {orders.map(o => (
            <tr key={o.id}><td><b>{o.id}</b></td><td className="muted">{dateFmt(o.placedAt)}</td><td><StatusBadge status={o.status} /></td><td className="num">{money(o.total)}</td></tr>
          ))}
          {orders.length === 0 && <tr><td className="muted">No orders linked.</td></tr>}
        </tbody>
      </table>
    </Modal>
  );
}
window.CrmPage = CrmPage;
