/* AIWine CRM — Regional promo codes: create/manage the member promo codes the
   website validates via validate_promo. Each code carries its own % AND its own
   expiry, so "5% for a month" or "10% for 2 weeks" is just data on the row.
   Live: reads/writes the promo_codes table. Demo: works on the local cache. */
function PromoCodes({ country }) {
  const store = window.UI.useStore();
  const { Field, toast, Ic, Empty } = window.UI;
  const [adding, setAdding] = React.useState(false);
  const rows = (store.t('promo_codes') || []).slice().sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
  const now = Date.now();
  const status = (r) => {
    if (r.active === false) return { label: 'Disabled', c: 'var(--muted)' };
    const exp = Date.parse(r.expires_at);
    if (exp && now > exp) return { label: 'Expired', c: 'var(--claret)' };
    const starts = Date.parse(r.starts_at);
    if (starts && now < starts) return { label: 'Scheduled', c: 'var(--brass)' };
    return { label: 'Active', c: 'var(--green)' };
  };
  const fmt = (d) => { const t = Date.parse(d); return t ? new Date(t).toLocaleDateString('en-NZ', { day: 'numeric', month: 'short', year: 'numeric' }) : '—'; };
  const toggle = async (r) => { try { await store.update('promo_codes', r.code, { active: !(r.active !== false) }); toast(r.active !== false ? 'Disabled ' + r.code : 'Enabled ' + r.code); } catch (e) { toast(e.message); } };
  const remove = async (r) => { if (!confirm('Delete promo code ' + r.code + '?')) return; try { await store.remove('promo_codes', r.code); toast('Deleted ' + r.code); } catch (e) { toast(e.message); } };

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{rows.filter((r) => status(r).label === 'Active').length} active</div>
          <h1 className="page-title">Promo codes</h1>
        </div>
        <button className="btn btn-primary" onClick={() => setAdding(true)}><Ic name="plus" w={15} /> New code</button>
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--muted)', marginBottom: 16, maxWidth: 620, lineHeight: 1.55 }}>
        Regional promo codes give <b>AIWine Members</b> an extra discount at checkout. Each code sets its own percentage and its own expiry — enter it once here and it works on the website and app until it lapses.
      </div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Code</th><th>Discount</th><th>Label / region</th><th>Valid until</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {rows.map((r) => { const st = status(r); return (
              <tr key={r.code}>
                <td className="main-cell mono">{r.code}</td>
                <td className="num">{r.pct}%</td>
                <td>{r.label || '—'}{r.region ? <div className="sub">{r.region}</div> : null}</td>
                <td>{fmt(r.expires_at)}</td>
                <td><span className="badge" style={{ color: st.c }}>{st.label}</span></td>
                <td onClick={(e) => e.stopPropagation()} style={{ whiteSpace: 'nowrap', textAlign: 'right' }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => toggle(r)}>{r.active !== false ? 'Disable' : 'Enable'}</button>
                  <button className="btn-quiet" style={{ color: 'var(--claret)', marginLeft: 6 }} onClick={() => remove(r)}>Delete</button>
                </td>
              </tr>
            ); })}
            {rows.length === 0 && <tr><td colSpan="6"><Empty msg="No promo codes yet" hint="Create one for a regional launch." /></td></tr>}
          </tbody>
        </table>
      </div>
      {adding && <AddPromo onClose={() => setAdding(false)} />}
    </div>
  );
}

function AddPromo({ onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const [f, setF] = React.useState({ code: '', pct: 10, label: '', region: '', weeks: 4 });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    const code = (f.code || '').trim().toUpperCase();
    if (!code) { toast('Give the code a name (e.g. WAIRARAPA5)'); return; }
    const pct = +f.pct; if (!(pct > 0 && pct <= 100)) { toast('Discount must be 1–100%'); return; }
    const wks = Math.max(1, +f.weeks || 4);
    const expires = new Date(Date.now() + wks * 7 * 86400000).toISOString();
    try {
      await store.insert('promo_codes', { code, pct, label: f.label.trim() || null, region: f.region.trim() || null, starts_at: new Date().toISOString(), expires_at: expires, active: true });
      if (store.audit) store.audit('Created promo code ' + code + ' (' + pct + '% for ' + wks + 'wk)', 'promo');
      toast('Promo code ' + code + ' created');
      onClose();
    } catch (err) { toast(err.message); }
  };
  return (
    <window.UI.Modal title="New promo code" sub="Member regional discount" onClose={onClose}
      foot={<React.Fragment><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" onClick={save}>Create code</button></React.Fragment>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Code (customers type this)"><input className="input" value={f.code} onChange={set('code')} placeholder="WAIRARAPA5" style={{ textTransform: 'uppercase' }} autoFocus /></Field>
        <div className="grid-2">
          <Field label="Discount %"><input className="input" type="number" min="1" max="100" value={f.pct} onChange={set('pct')} /></Field>
          <Field label="Valid for (weeks)"><input className="input" type="number" min="1" value={f.weeks} onChange={set('weeks')} /></Field>
        </div>
        <div className="grid-2">
          <Field label="Label"><input className="input" value={f.label} onChange={set('label')} placeholder="Wairarapa launch" /></Field>
          <Field label="Region (optional)"><input className="input" value={f.region} onChange={set('region')} placeholder="Wairarapa" /></Field>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)' }}>The code gives AIWine Members {f.pct || 0}% off, valid until {new Date(Date.now() + Math.max(1, +f.weeks || 4) * 7 * 86400000).toLocaleDateString('en-NZ', { day: 'numeric', month: 'short', year: 'numeric' })}.</div>
      </div>
    </window.UI.Modal>
  );
}
window.PromoCodes = PromoCodes;
