/* ============================================================
   ELECTROMED — Machine Serial Register
   Per-serial machine record + service timeline (R1..R5). Live from /serials.
   ============================================================ */
function Serials({ branch }) {
  const { PKR } = window.DATA;
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(null);
  const [add, setAdd] = useState(false);
  const bf = () => ({ ...(branch !== 'All' ? { branch_id: branch } : {}), search: q || undefined });
  const { data, loading, refetch } = useFetch(() => api.getSerials(bf()), [branch, q]);
  const rows = (data && data.rows) || [];

  return (
    <div className="view-enter">
      <PageHead eyebrow="06 · Assets" title="Serial Register"
        sub="Every machine tracked by serial number, with its full service history."
        actions={window.can('inventory', 'create') && <Btn variant="primary" icon={<Icons.plus size={16} />} onClick={() => setAdd(true)}>Add Serial</Btn>} />

      <div className="grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 18 }}>
        <StatCard icon={<Icons.box size={18} />} label="Registered Machines" value={data ? data.count : '—'} />
        <StatCard icon={<Icons.wrench size={18} />} label="With Service History" value={rows.filter(r => r.service_count > 0).length} />
        <StatCard icon={<Icons.rental size={18} />} label="Active" value={rows.filter(r => r.status === 'active').length} />
      </div>

      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', paddingBottom: 12 }}>
          <div style={{ fontWeight: 800, fontSize: 16 }}>Machines</div>
          <SearchBox value={q} onChange={setQ} placeholder="Serial, model, customer…" w={240} />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr><th>Serial</th><th>Model</th><th>Customer</th><th>Sale Date</th><th>Source</th><th style={{ textAlign: 'right' }}>Services</th><th></th></tr></thead>
            <tbody>
              {loading && !rows.length ? <tr><td colSpan="7" className="muted tiny" style={{ padding: 20, textAlign: 'center' }}>Loading…</td></tr>
                : !rows.length ? <tr><td colSpan="7" className="muted tiny" style={{ padding: 20, textAlign: 'center' }}>No machines registered.</td></tr>
                : rows.map(r => (
                  <tr key={r.id} style={{ cursor: 'pointer' }} onClick={() => setSel(r)}>
                    <td className="mono" style={{ fontWeight: 700 }}>{r.serial}</td>
                    <td>{r.model || '—'}</td>
                    <td>{r.customer_name || '—'}</td>
                    <td className="tiny muted">{r.sale_date || '—'}</td>
                    <td><Badge kind="idle">{r.source}</Badge></td>
                    <td className="mono" style={{ textAlign: 'right' }}>{r.service_count}</td>
                    <td style={{ textAlign: 'right' }}><Icons.chevD size={14} style={{ transform: 'rotate(-90deg)', color: 'var(--ink-3)' }} /></td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      </div>

      {sel && <SerialDetail id={sel.id} onClose={() => setSel(null)} onChanged={refetch} />}
      {add && <SerialModal branch={branch} onClose={() => setAdd(false)} onSaved={() => { setAdd(false); refetch(); }} />}
    </div>
  );
}

function SerialDetail({ id, onClose, onChanged }) {
  const { data, refetch } = useFetch(() => api.getSerial(id), [id]);
  const [addEv, setAddEv] = useState(false);
  const s = data && data.serial;
  return (
    <Modal title={s ? `Serial ${s.serial}` : 'Loading…'} sub={s ? `${s.model || '—'} · ${s.customer_name || '—'}` : ''} wide onClose={onClose}
      foot={window.can('inventory', 'edit') && <Btn variant="primary" icon={<Icons.plus size={15} />} onClick={() => setAddEv(true)}>Add Service Event</Btn>}>
      {!s ? <div className="tiny muted">Loading…</div> : <>
        <div className="grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 16 }}>
          <Meta label="Model" value={s.model} /><Meta label="Sale Date" value={s.sale_date} /><Meta label="Source" value={s.source} />
        </div>
        <div style={{ fontWeight: 800, fontSize: 14, marginBottom: 10 }}>Service Timeline</div>
        {(!s.events || !s.events.length) ? <div className="tiny muted">No service events yet.</div> : (
          <div style={{ display: 'grid', gap: 8 }}>
            {s.events.map((e, i) => (
              <div key={i} className="row" style={{ gap: 12, padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 10 }}>
                <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12, flexShrink: 0 }}>R{e.seq}</div>
                <div className="grow"><div style={{ fontWeight: 600 }}>{e.action || '—'}</div><div className="tiny muted">{e.date || '—'}{e.hours ? ` · ${e.hours} hrs` : ''}</div></div>
              </div>
            ))}
          </div>
        )}
        {addEv && <EventModal serialId={s.id} nextSeq={(s.events || []).reduce((m, e) => Math.max(m, e.seq), 0) + 1} onClose={() => setAddEv(false)} onSaved={() => { setAddEv(false); refetch(); onChanged && onChanged(); }} />}
      </>}
    </Modal>
  );
}
function Meta({ label, value }) {
  return <div style={{ border: '1px solid var(--line)', borderRadius: 10, padding: '10px 12px' }}>
    <div className="tiny muted" style={{ fontWeight: 700 }}>{label}</div><div style={{ fontWeight: 700, marginTop: 2 }}>{value || '—'}</div></div>;
}

function SerialModal({ branch, onClose, onSaved }) {
  const [f, setF] = useState({ serial: '', model: '', customer_name: '', sale_date: '', source: 'sale' });
  const [busy, setBusy] = useState(false);
  const set = k => e => setF(s => ({ ...s, [k]: e.target.value }));
  const save = async () => {
    if (!f.serial.trim()) return window.toast('Serial number is required', 'warn');
    setBusy(true);
    try { await api.createSerial({ ...f, branch_id: branch !== 'All' ? branch : undefined }); window.toast('Serial registered', 'ok'); onSaved(); }
    catch (e) { window.toast(e.message, 'error'); setBusy(false); }
  };
  return <Modal title="Register Machine Serial" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save'}</Btn></>}>
    <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <label className="fld" style={{ gridColumn: '1 / -1' }}><span>Serial # *</span><input className="input-block mono" value={f.serial} onChange={set('serial')} /></label>
      <label className="fld"><span>Model</span><input className="input-block" value={f.model} onChange={set('model')} placeholder="e.g. SimplyGo Mini" /></label>
      <label className="fld"><span>Customer</span><input className="input-block" value={f.customer_name} onChange={set('customer_name')} /></label>
      <label className="fld"><span>Sale Date</span><input className="input-block" type="date" value={f.sale_date} onChange={set('sale_date')} /></label>
      <label className="fld"><span>Source</span><select className="input-block" value={f.source} onChange={set('source')}><option value="sale">Sale</option><option value="rental">Rental</option><option value="workshop">Workshop</option></select></label>
    </div>
  </Modal>;
}

function EventModal({ serialId, nextSeq, onClose, onSaved }) {
  const [f, setF] = useState({ seq: nextSeq, date: '', hours: '', action: '' });
  const [busy, setBusy] = useState(false);
  const set = k => e => setF(s => ({ ...s, [k]: e.target.value }));
  const save = async () => {
    if (!f.action.trim()) return window.toast('Action is required', 'warn');
    setBusy(true);
    try { await api.addSerialEvent(serialId, { ...f, hours: Number(f.hours) || 0, seq: Number(f.seq) || undefined }); window.toast('Service event added', 'ok'); onSaved(); }
    catch (e) { window.toast(e.message, 'error'); setBusy(false); }
  };
  return <Modal title="Add Service Event" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save'}</Btn></>}>
    <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <label className="fld"><span>Cycle (R#)</span><input className="input-block mono" type="number" value={f.seq} onChange={set('seq')} /></label>
      <label className="fld"><span>Date</span><input className="input-block" type="date" value={f.date} onChange={set('date')} /></label>
      <label className="fld"><span>Hours</span><input className="input-block mono" type="number" value={f.hours} onChange={set('hours')} /></label>
      <label className="fld" style={{ gridColumn: '1 / -1' }}><span>Action *</span><input className="input-block" value={f.action} onChange={set('action')} placeholder="e.g. Sieves + Filter replace" /></label>
    </div>
  </Modal>;
}

window.Serials = Serials;
