/* ============================================================
   ELECTROMED — Workshop / Service + Job Card Workflow
   Received → Job Card → Diagnose & Repair → Bill → Closed
   ============================================================ */

function normalizeJob(j) {
  return {
    ...j,
    no: j.job_number || j.no,
    cust: j.customer_name || j.cust,
    parts: typeof j.parts_json === 'string'
      ? JSON.parse(j.parts_json || '[]')
      : (j.parts || []),
    hours: Number(j.hours) || 0,
  };
}

function Workshop({ branch }) {
  const D = window.DATA; const { PKR } = D;
  const [view, setView] = useState('Board');
  const [sel, setSel] = useState(null);
  const [wf, setWf] = useState(false);
  const [warranty, setWarranty] = useState(false);
  const [rec, setRec] = useState(null);

  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: branchList } = useBranches();
  const { data: rawJobs, refetch: refetchJobs } = useWorkshopJobs(bf);

  const jobs = rawJobs
    .map(j => ({ ...normalizeJob(j), branchName: (branchList.find(b => String(b.id) === String(j.branch_id)) || {}).city || '—' }));

  const cols = ['Diagnosing', 'Awaiting Parts', 'In Repair', 'Billed', 'Closed'];
  const open = jobs.filter(j => j.status !== 'Closed').length;

  return (
    <div className="view-enter">
      <PageHead eyebrow="04 · Workshop / Service" title="Workshop & Repairs"
        sub="Job cards, parts installed, warranty claims, CPAP titration and service."
        actions={<>
          <div className="tabs">
            <button className={cls('tab', view==='Board'&&'active')} onClick={()=>setView('Board')}>Board</button>
            <button className={cls('tab', view==='List'&&'active')} onClick={()=>setView('List')}>List</button>
            <button className={cls('tab', view==='Bills'&&'active')} onClick={()=>setView('Bills')}>Bills</button>
            <button className={cls('tab', view==='Records'&&'active')} onClick={()=>setView('Records')}>Service Records</button>
          </div>
          <Btn variant="ghost" icon={<Icons.shield size={16} />} onClick={() => setWarranty(true)}>Warranty Check</Btn>
          {window.can('workshop','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setWf(true)}>New Job Card</Btn>}
        </>} />

      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.wrench size={18} />} label="Open Job Cards" value={open} sub="in workshop" />
        <StatCard icon={<Icons.box size={18} />} label="Awaiting Parts" value={jobs.filter(j=>j.status==='Awaiting Parts').length} accent />
        <StatCard icon={<Icons.shield size={18} />} label="Warranty Claims" value={jobs.filter(j=>/warranty|claim/i.test(j.claim||'')).length} sub="OEM / Dynmed" />
        <StatCard icon={<Icons.clock size={18} />} label="Hours Logged" value={jobs.reduce((s,j)=>s+j.hours,0).toFixed(1)} sub="this month" />
      </div>

      {view === 'Records' ? (
        <ServiceRecords branch={branch} onOpen={setRec} />
      ) : view === 'Bills' ? (
        <BillsView branch={branch} onOpen={setSel} />
      ) : view === 'Board' ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, alignItems: 'start' }}>
          {cols.map((col) => {
            const items = jobs.filter(j => j.status === col);
            return (
              <div key={col} style={{ background: 'var(--surface-2)', borderRadius: 16, padding: 12, border: '1px solid var(--line)' }}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12, padding: '2px 4px' }}>
                  <span className="row" style={{ gap: 7, fontWeight: 700, fontSize: 13 }}>
                    <span className="dot" style={{ background: `var(--${({Diagnosing:'info','Awaiting Parts':'warn','In Repair':'info',Billed:'ok',Closed:'idle'})[col]})` }} />{col}
                  </span>
                  <span className="tiny muted" style={{ fontWeight: 700 }}>{items.length}</span>
                </div>
                <div style={{ display: 'grid', gap: 10 }}>
                  {items.map(j => (
                    <button key={j.no} onClick={() => setSel(j)} style={{ textAlign: 'left', background: '#fff', border: '1px solid var(--line)', borderRadius: 12, padding: 12, boxShadow: 'var(--sh-sm)' }}>
                      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
                        <span className="mono tiny" style={{ fontWeight: 800 }}>{j.no}</span>
                        <span className="tiny muted">{j.hours}h</span>
                      </div>
                      <div style={{ fontWeight: 700, fontSize: 13, lineHeight: 1.3, marginBottom: 4 }}>{j.issue}</div>
                      <div className="tiny muted" style={{ marginBottom: 8 }}>{j.device}</div>
                      <div className="row" style={{ justifyContent: 'space-between' }}>
                        <span className="tiny" style={{ fontWeight: 600 }}>{(j.cust||'').split(' ').slice(0,2).join(' ')}</span>
                        <Badge kind={/warranty|claim/i.test(j.claim||'')?'info':'idle'}>
                          {/warranty/i.test(j.claim||'')?'OEM':/claim/i.test(j.claim||'')?'Claim':'Paid'}
                        </Badge>
                      </div>
                    </button>
                  ))}
                  {!items.length && <div className="tiny muted" style={{ textAlign: 'center', padding: '14px 0' }}>—</div>}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Job Card</th><th>Customer</th><th>Device / Serial</th><th>Issue</th><th>Claim</th><th>Hours</th><th>Status</th></tr></thead>
            <tbody>
              {jobs.map(j => (
                <tr key={j.no} style={{ cursor: 'pointer' }} onClick={() => setSel(j)}>
                  <td className="mono" style={{ fontWeight: 700 }}>{j.no}</td>
                  <td style={{ fontWeight: 600 }}>{j.cust}</td>
                  <td><div style={{ fontWeight: 600 }}>{j.device}</div><div className="tiny muted mono">{j.serial}</div></td>
                  <td className="muted">{j.issue}</td>
                  <td><Badge kind={/warranty|claim/i.test(j.claim||'')?'info':'idle'}>{j.claim}</Badge></td>
                  <td className="mono">{j.hours}h</td>
                  <td><Badge kind={window.statusKind(j.status)}>{j.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {sel && <JobCardDetail j={sel} onClose={() => { setSel(null); refetchJobs(); }} onRefetch={refetchJobs} />}
      {wf && <JobWorkflow onClose={() => { setWf(false); refetchJobs(); }} />}
      {warranty && <WarrantyCheck onClose={() => setWarranty(false)} />}
      {rec && <ServiceRecordDetail r={rec} onClose={() => setRec(null)} />}
    </div>
  );
}

/* ---------- Service Records table view ---------- */
function ServiceRecords({ branch, onOpen }) {
  const D = window.DATA;
  const [q, setQ] = useState('');
  const records = D.serviceRecords || [];
  const list = records.filter((r) =>
    (r.serial||'').toLowerCase().includes(q.toLowerCase()) ||
    (r.device||'').toLowerCase().includes(q.toLowerCase()) ||
    (r.cust||'').toLowerCase().includes(q.toLowerCase())
  );
  const today = new Date();
  const wkStatus = (exp) => {
    const d = (new Date(exp) - today) / 86400000;
    return d < 0 ? ['Expired', 'bad'] : d < 60 ? ['Expiring soon', 'warn'] : ['In warranty', 'ok'];
  };
  return (
    <div className="card">
      <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
        <div style={{ fontWeight: 800, fontSize: 15 }}>Machine Service Records</div>
        <SearchBox value={q} onChange={setQ} placeholder="Serial, device or customer…" w={260} />
      </div>
      <div style={{ overflowX: 'auto' }}>
        <table className="tbl">
          <thead><tr><th>Serial</th><th>Device</th><th>Owner</th><th>Warranty</th><th>Expiry</th><th>Services</th><th></th></tr></thead>
          <tbody>
            {list.map((r) => {
              const [lbl, kind] = wkStatus(r.expiry);
              return (
                <tr key={r.serial} style={{ cursor: 'pointer' }} onClick={() => onOpen(r)}>
                  <td className="mono" style={{ fontWeight: 700 }}>{r.serial}</td>
                  <td style={{ fontWeight: 600 }}>{r.device}</td>
                  <td className="muted">{r.cust}</td>
                  <td className="tiny"><div className="row" style={{ gap: 5 }}><Icons.shield size={13} style={{ color: 'var(--lime-700)' }} />{r.warranty}</div></td>
                  <td><Badge kind={kind}>{lbl}</Badge></td>
                  <td className="mono">{(r.services||[]).length}</td>
                  <td><Icons.chevR size={16} style={{ color: 'var(--ink-3)' }} /></td>
                </tr>
              );
            })}
            {!list.length && <tr><td colSpan={7} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No records found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------- Service record detail (per machine history) ---------- */
function ServiceRecordDetail({ r, onClose }) {
  const { PKR } = window.DATA;
  const today = new Date();
  const days = Math.round((new Date(r.expiry) - today) / 86400000);
  const inWarranty = days >= 0;
  return (
    <Modal wide title={`Service Record · ${r.serial}`} sub={`${r.device} · ${r.cust}`} onClose={onClose}
      foot={<><Btn variant="ghost" icon={<Icons.print size={16} />}>Print History</Btn><Btn variant="primary" icon={<Icons.plus size={16} />}>Add Service Entry</Btn></>}>
      <div className="row" style={{ gap: 10, padding: '14px 16px', borderRadius: 12, marginBottom: 16, background: inWarranty ? 'var(--ok-bg)' : 'var(--bad-bg)' }}>
        <Icons.shield size={22} style={{ color: inWarranty ? 'var(--ok)' : 'var(--bad)' }} />
        <div className="grow">
          <div style={{ fontWeight: 800, color: inWarranty ? 'var(--ok)' : 'var(--bad)' }}>{inWarranty ? `Under warranty · ${days} days left` : `Warranty expired ${-days} days ago`}</div>
          <div className="tiny muted">{r.warranty} · purchased {r.purchased} · expires {r.expiry}</div>
        </div>
      </div>
      <div style={{ fontWeight: 800, marginBottom: 8 }}>Service & Repair History</div>
      <div style={{ display: 'grid', gap: 10 }}>
        {(r.services||[]).map((s, ix) => (
          <div key={ix} style={{ border: '1px solid var(--line)', borderRadius: 12, padding: '12px 14px' }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 5 }}>
              <span className="row" style={{ gap: 8, fontWeight: 700 }}>
                <Badge kind={s.type === 'Repair' ? 'info' : s.type === 'Titration' ? 'warn' : 'idle'}>{s.type}</Badge>{s.detail}
              </span>
              <span className="tiny muted mono">{s.date}</span>
            </div>
            <div className="row" style={{ justifyContent: 'space-between', marginTop: 6 }}>
              <span className="tiny muted">By {s.by} · {s.claim}</span>
              <span className="mono tiny" style={{ fontWeight: 700, color: s.cost === 0 ? 'var(--ok)' : 'var(--ink)' }}>{s.cost === 0 ? 'No charge (claim)' : PKR(s.cost)}</span>
            </div>
          </div>
        ))}
        {!(r.services||[]).length && <div className="tiny muted">No service history recorded.</div>}
      </div>
    </Modal>
  );
}

/* ---------- Warranty check lookup ---------- */
function WarrantyCheck({ onClose }) {
  const D = window.DATA;
  const { data: invoices } = useInvoices();
  const [serial, setSerial] = useState('');
  const [result, setResult] = useState(null);
  const today = new Date();
  const serviceRecords = D.serviceRecords || [];

  const run = () => {
    const fromRecords = serviceRecords.find(r => r.serial.toLowerCase() === serial.trim().toLowerCase());
    const fromInvoice = invoices
      .filter(i => i.serial && i.serial !== '—')
      .map(i => ({ serial: i.serial, device: i.device || '—', cust: i.customer_name || '—', warranty: i.warranty || '—', expiry: i.expiry || '—', purchased: i.date, services: [] }))
      .find(r => r.serial.toLowerCase() === serial.trim().toLowerCase());
    setResult(fromRecords || fromInvoice || 'none');
  };

  const days = result && result !== 'none' && result.expiry !== '—' ? Math.round((new Date(result.expiry) - today) / 86400000) : null;
  const inW = days != null && days >= 0;
  return (
    <Modal title="Warranty Check" sub="Look up coverage by machine serial" onClose={onClose}
      foot={<><Btn variant="ghost" onClick={onClose}>Close</Btn><Btn variant="primary" icon={<Icons.search size={16} />} onClick={run}>Check Warranty</Btn></>}>
      <label className="fld" style={{ marginBottom: 14 }}><span>Machine Serial Number</span>
        <input className="input-block mono" placeholder="e.g. AC10-77231" value={serial} onChange={(e) => setSerial(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && run()} />
      </label>
      <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
        <span className="tiny muted">Try:</span>
        {serviceRecords.slice(0, 3).map(r => <button key={r.serial} className="badge" style={{ background: 'var(--surface-3)', color: 'var(--ink-2)' }} onClick={() => setSerial(r.serial)}>{r.serial}</button>)}
      </div>
      {result === 'none' && (
        <div className="row" style={{ gap: 10, padding: '14px 16px', borderRadius: 12, background: 'var(--idle-bg)' }}>
          <Icons.help size={20} style={{ color: 'var(--ink-3)' }} />
          <div><div style={{ fontWeight: 700 }}>No machine found</div><div className="tiny muted">That serial isn't on record. Check the number or register the sale first.</div></div>
        </div>
      )}
      {result && result !== 'none' && (
        <div style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
          <div className="row" style={{ justifyContent: 'space-between', padding: '14px 16px', background: inW ? 'var(--ok-bg)' : 'var(--bad-bg)' }}>
            <span className="row" style={{ gap: 9, fontWeight: 800, color: inW ? 'var(--ok)' : 'var(--bad)' }}><Icons.shield size={18} />{inW ? 'In Warranty' : 'Out of Warranty'}</span>
            {days != null && <span className="tiny" style={{ fontWeight: 700, color: inW ? 'var(--ok)' : 'var(--bad)' }}>{inW ? `${days} days left` : `expired ${-days}d ago`}</span>}
          </div>
          <div style={{ padding: 16 }}>
            {[['Device', result.device], ['Owner', result.cust], ['Coverage', result.warranty], ['Expiry', result.expiry]].map(([k, v]) => (
              <div key={k} className="row" style={{ justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--line)' }}>
                <span className="muted tiny">{k}</span><span style={{ fontWeight: 700 }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </Modal>
  );
}

function JobCardDetail({ j, onClose, onRefetch }) {
  const D = window.DATA; const { PKR } = D;
  const stages = ['Diagnosing', 'Awaiting Parts', 'In Repair', 'Billed', 'Closed'];
  const cur = stages.indexOf(j.status);
  const docRef = useRef(null);
  const [showBill,   setShowBill]   = useState(false);
  const [newStatus,  setNewStatus]  = useState(j.status);
  const [updating,   setUpdating]   = useState(false);
  const [confirmDel, setConfirmDel] = useState(false);
  const bill = D.jobBill(j);

  const canDelete = ['Billed', 'Closed'].includes(j.status);

  const updateStatus = async () => {
    if (newStatus === j.status) return;
    setUpdating(true);
    try {
      await api.updateWorkshopJob(j.id, { status: newStatus });
      window.toast(`Job card status updated to ${newStatus}`, 'ok');
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to update status', 'error');
      setUpdating(false);
    }
  };

  if (confirmDel) return (
    <ConfirmDeleteModal
      title="Delete Job Card?"
      body={<>Permanently remove <strong>{j.no}</strong> for {j.cust}? This cannot be undone.</>}
      onCancel={() => setConfirmDel(false)}
      onConfirm={async () => {
        await api.deleteWorkshopJob(j.id);
        window.toast('Job card deleted', 'ok');
        onRefetch?.();
        onClose();
      }}
    />
  );

  return (
    <Modal wide title={`Job Card ${j.no}`} sub={`${j.cust} · opened ${j.opened}`} onClose={onClose}
      foot={<>
        {canDelete && window.can('workshop','delete') && (
          <Btn variant="danger" icon={<Icons.trash size={15} />} onClick={() => setConfirmDel(true)}>Delete</Btn>
        )}
        <Btn variant="ghost" icon={<Icons.print size={16}/>} onClick={() => window.printDocument(docRef.current)}>Print JC</Btn>
        <select className="input-block" style={{ width: 160, padding: '7px 10px', fontSize: 13 }} value={newStatus} onChange={e => setNewStatus(e.target.value)}>
          {stages.map(s => <option key={s}>{s}</option>)}
        </select>
        <Btn variant="dark" onClick={updateStatus} disabled={updating || newStatus === j.status}>{updating ? 'Saving…' : 'Update Status'}</Btn>
        {window.can('workshop','edit') && <Btn variant="primary" icon={<Icons.doc size={16}/>} onClick={() => setShowBill(true)}>Generate Bill</Btn>}
      </>}>
      <div ref={docRef}>
        <div style={{ background: 'var(--surface-2)', borderRadius: 14, padding: 16, marginBottom: 16 }}>
          <div style={{ fontWeight: 800 }}>{j.device}</div>
          <div className="tiny muted mono" style={{ marginTop: 3 }}>Serial · {j.serial} · {j.branchName || j.branch_id}</div>
          <div style={{ marginTop: 10, fontWeight: 600 }}>Reported issue: <span className="muted" style={{ fontWeight: 500 }}>{j.issue}</span></div>
        </div>
        <div className="row" style={{ marginBottom: 18 }}>
          {stages.map((s, ix) => (
            <React.Fragment key={s}>
              <div style={{ flex: 1, textAlign: 'center' }}>
                <div style={{ width: 26, height: 26, borderRadius: 50, margin: '0 auto', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 800, background: ix<=cur?'var(--lime)':'var(--surface-3)', color: ix<=cur?'var(--forest-2)':'var(--ink-3)' }}>
                  {ix<cur?<Icons.check size={14} stroke={3}/>:ix+1}
                </div>
                <div className="tiny" style={{ marginTop: 5, fontWeight: ix===cur?700:500, color: ix<=cur?'var(--ink)':'var(--ink-3)' }}>{s}</div>
              </div>
            </React.Fragment>
          ))}
        </div>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}><div className="tiny muted" style={{fontWeight:700}}>Warranty / Claim</div><div style={{fontWeight:700, marginTop:4}}>{j.claim}</div></div>
          <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}><div className="tiny muted" style={{fontWeight:700}}>Hours Logged</div><div style={{fontWeight:700, marginTop:4}} className="mono">{j.hours} hrs</div></div>
        </div>
        <div style={{ fontWeight: 800, margin: '16px 0 8px' }}>Parts Installed</div>
        {j.parts.length ? (
          <div style={{ display: 'grid', gap: 8 }}>
            {j.parts.map((p,ix) => (
              <div key={ix} className="row" style={{ justifyContent: 'space-between', background: 'var(--surface-2)', borderRadius: 10, padding: '10px 14px' }}>
                <span className="row" style={{gap:8}}><Icons.box size={16} style={{color:'var(--ink-3)'}}/>{p}</span>
                <Icons.check size={16} style={{color:'var(--lime-700)'}}/>
              </div>
            ))}
          </div>
        ) : <div className="tiny muted">No parts required — service / cleaning only.</div>}
      </div>

      {showBill && <ServiceBill j={j} onClose={() => setShowBill(false)} />}
    </Modal>
  );
}

/* ---------- Workshop Bills list ---------- */
function BillsView({ branch, onOpen }) {
  const D = window.DATA; const { PKR } = D;
  const [q, setQ] = useState('');
  const { data: branchList } = useBranches();
  const { data: rawJobs } = useWorkshopJobs();

  const branchObj = branch === 'All' ? null
    : branchList.find(b => (b.city || '').toLowerCase() === branch.toLowerCase());

  const jobs = rawJobs
    .map(normalizeJob)
    .filter(j =>
      (!branchObj || j.branch_id === branchObj.id) &&
      ((j.no||'').toLowerCase().includes(q.toLowerCase()) || (j.cust||'').toLowerCase().includes(q.toLowerCase()))
    );

  const billed = jobs.map(j => ({ j, b: D.jobBill(j) }));
  const chargeable = billed.reduce((s, x) => s + x.b.total, 0);
  const claimValue = billed.filter(x => x.b.covered).reduce((s, x) => s + x.b.partsTotal + x.b.labour, 0);

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 18 }}>
        <StatCard icon={<Icons.doc size={18} />} label="Service Bills" value={billed.length} sub="job cards" />
        <StatCard icon={<Icons.sales size={18} />} label="Chargeable (incl. GST)" value={PKR(chargeable)} accent />
        <StatCard icon={<Icons.shield size={18} />} label="Billed to OEM / Claim" value={PKR(claimValue)} sub="warranty covered" />
      </div>
      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <div style={{ fontWeight: 800, fontSize: 15 }}>Service &amp; Repair Bills</div>
          <SearchBox value={q} onChange={setQ} placeholder="Bill, job card or customer…" w={260} />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr><th>Bill / Job</th><th>Customer</th><th>Device / Serial</th><th>Parts + Labour</th><th>Coverage</th><th style={{ textAlign: 'right' }}>Chargeable</th><th></th></tr></thead>
            <tbody>
              {billed.map(({ j, b }) => (
                <tr key={j.no} style={{ cursor: 'pointer' }} onClick={() => onOpen(j)}>
                  <td><div className="mono" style={{ fontWeight: 700 }}>BILL-{(j.no||'').replace('JC-', '')}</div><div className="tiny muted mono">{j.no}</div></td>
                  <td style={{ fontWeight: 600 }}>{j.cust}</td>
                  <td><div style={{ fontWeight: 600 }}>{j.device}</div><div className="tiny muted mono">{j.serial}</div></td>
                  <td className="mono tiny">{PKR(b.partsTotal)} + {PKR(b.labour)}</td>
                  <td><Badge kind={b.covered ? 'info' : 'idle'}>{b.covered ? 'OEM / Claim' : 'Paid'}</Badge></td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: b.covered ? 'var(--ok)' : 'var(--ink)' }}>{b.covered ? 'No charge' : PKR(b.total)}</td>
                  <td><Icons.chevR size={16} style={{ color: 'var(--ink-3)' }} /></td>
                </tr>
              ))}
              {!billed.length && <tr><td colSpan={7} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No bills found.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ---------- Printable Service / Repair Bill ---------- */
function ServiceBill({ j, onClose }) {
  const D = window.DATA; const { PKR } = D;
  const { data: companies } = useCompanies();
  const defaultCo = { name: 'Electromed Corporation', color: '#1a1a2e', letterhead: '', addr: '', phone: '', email: '', bank: '' };
  const co = companies.find(c => c.id === (j.company || j.company_id || '')) || companies[0] || defaultCo;
  const b = D.jobBill(j);
  const docRef = useRef(null);
  const billNo = 'BILL-' + (j.no||'').replace('JC-', '');

  return (
    <Modal wide title={`Service Bill · ${j.no}`} sub={`${j.cust} · ${j.device}`} onClose={onClose}
      foot={<>
        <Btn variant="ghost" icon={<Icons.download size={16} />} onClick={() => window.printDocument(docRef.current)}>Download PDF</Btn>
        <Btn variant="ghost" icon={<Icons.print size={16} />} onClick={() => window.printDocument(docRef.current)}>Print</Btn>
        {!b.covered && <Btn variant="primary" icon={<Icons.pay size={16} />}>Record Payment</Btn>}
      </>}>
      <div ref={docRef} style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', background: co.color, color: '#fff', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div className="row" style={{ gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,.12)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>{co.name}</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.7)', marginTop: 2 }}>{co.letterhead}</div>
              <div className="tiny" style={{ color: 'rgba(255,255,255,.55)', marginTop: 6, lineHeight: 1.5 }}>{co.addr}<br />{co.phone} · {co.email}</div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: '.04em' }}>SERVICE BILL</div>
            <div className="tiny mono" style={{ color: 'rgba(255,255,255,.8)', marginTop: 4 }}>{billNo}</div>
            <div className="tiny" style={{ color: 'rgba(255,255,255,.55)', marginTop: 6 }}>Job card {j.no} · {j.opened}</div>
          </div>
        </div>

        <div style={{ padding: '16px 22px', display: 'flex', justifyContent: 'space-between', gap: 18, flexWrap: 'wrap', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 4 }}>BILL TO</div>
            <div style={{ fontWeight: 700 }}>{j.cust}</div>
            <div className="tiny muted">{j.device} · {j.serial}</div>
            <div className="tiny muted">Issue · {j.issue}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 4 }}>COVERAGE</div>
            <Badge kind={b.covered ? 'info' : 'idle'}>{j.claim}</Badge>
            {co.ntn && <div className="tiny mono" style={{ marginTop: 6 }}>NTN · {co.ntn}</div>}
          </div>
        </div>

        <table className="tbl" style={{ fontSize: 13 }}>
          <thead><tr><th>Description</th><th style={{ textAlign: 'right' }}>Qty</th><th style={{ textAlign: 'right' }}>Rate</th><th style={{ textAlign: 'right' }}>Amount</th></tr></thead>
          <tbody>
            {b.parts.map((p, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 600 }}>{p.name}<div className="tiny muted">Spare part</div></td>
                <td className="mono" style={{ textAlign: 'right' }}>{p.qty}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(p.price)}</td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(p.price * p.qty)}</td>
              </tr>
            ))}
            <tr>
              <td style={{ fontWeight: 600 }}>Labour &amp; service<div className="tiny muted">technician time</div></td>
              <td className="mono" style={{ textAlign: 'right' }}>{b.hours}h</td>
              <td className="mono" style={{ textAlign: 'right' }}>{PKR(b.labourRate)}/h</td>
              <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(b.labour)}</td>
            </tr>
          </tbody>
        </table>

        <div style={{ padding: '14px 22px', display: 'flex', justifyContent: 'flex-end' }}>
          <div style={{ width: 280 }}>
            <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0' }}><span className="muted tiny">Parts + labour</span><span className="mono" style={{ fontWeight: 600 }}>{PKR(b.partsTotal + b.labour)}</span></div>
            {b.covered
              ? <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line)' }}><span className="muted tiny">{j.claim} — billed to OEM</span><span className="mono" style={{ fontWeight: 600, color: 'var(--ok)' }}>−{PKR(b.partsTotal + b.labour)}</span></div>
              : b.tax > 0 && <div className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line)' }}><span className="muted tiny">GST @ {b.gstRate}%</span><span className="mono" style={{ fontWeight: 600 }}>{PKR(b.tax)}</span></div>}
            <div className="row" style={{ justifyContent: 'space-between', padding: '10px 0 4px' }}><span style={{ fontWeight: 800 }}>Customer Payable</span><span className="mono" style={{ fontWeight: 800, fontSize: 16 }}>{PKR(b.total)}</span></div>
          </div>
        </div>

        <div className="row" style={{ justifyContent: 'space-between', padding: '12px 22px', background: b.covered ? 'var(--ok-bg)' : (b.total > 0 ? 'var(--warn-bg)' : 'var(--ok-bg)') }}>
          <span style={{ fontWeight: 700, color: b.covered ? 'var(--ok)' : 'var(--warn)' }}>{b.covered ? 'No charge — warranty / claim covered' : 'Payment due on collection'}</span>
          <span className="mono" style={{ fontWeight: 800, fontSize: 18, color: b.covered ? 'var(--ok)' : 'var(--warn)' }}>{PKR(b.total)}</span>
        </div>
        <div className="tiny muted" style={{ padding: '10px 22px', borderTop: '1px solid var(--line)' }}>
          {b.covered ? 'Parts & labour claimed against manufacturer / supplier warranty — no charge to customer.' : 'Service bill payable on machine collection.'} Bank · {co.bank}
        </div>
      </div>
    </Modal>
  );
}

const JOB_STEPS = [
  { t: 'Machine Received', d: 'From client / branch' },
  { t: 'Create Job Card', d: 'JC# · serial · parts' },
  { t: 'Diagnose & Repair', d: 'Service / titration' },
  { t: 'Bill Generated', d: 'Warranty or paid' },
  { t: 'Closed & Delivered', d: 'Status notification' },
];

function JobWorkflow({ onClose }) {
  const D = window.DATA;
  const { data: customers } = useCustomers();
  const { data: products } = useProducts();
  const { data: inventory } = useInventory();
  const [step, setStep] = useState(0);
  const last = step === JOB_STEPS.length - 1;
  const spareParts = inventory.filter(i => (i.category || '').toLowerCase().includes('spare') || (i.category || '').toLowerCase().includes('part'));

  const [custId,      setCustId]      = useState('');
  const [deviceId,    setDeviceId]    = useState('');
  const [serial,      setSerial]      = useState('');
  const [issue,       setIssue]       = useState('');
  const [serviceType, setServiceType] = useState('Repair');
  const [claim,       setClaim]       = useState('Paid');
  const [selectedPart, setSelectedPart] = useState('');
  const [hours,       setHours]       = useState('');
  const [busy,        setBusy]        = useState(false);

  const submit = async () => {
    setBusy(true);
    try {
      const cust = customers.find(c => c.id === custId);
      const prod = products.find(p => p.id === deviceId);
      const jobNum = 'JC-' + Date.now().toString().slice(-6);
      const today = new Date().toISOString().slice(0, 10);
      await api.createWorkshopJob({
        job_number: jobNum,
        customer_id: custId || null,
        customer_name: cust ? cust.name : '',
        device: prod ? prod.name : '—',
        serial: serial || '—',
        issue: `[${serviceType}] ${issue || '—'}`,
        claim,
        status: 'Diagnosing',
        opened: today,
        parts_json: selectedPart ? JSON.stringify([selectedPart]) : '[]',
        hours: parseFloat(hours) || 0,
      });
      window.toast(`Job card ${jobNum} created`, 'ok');
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to create job card', 'error');
      setBusy(false);
    }
  };

  return (
    <Modal wide title="New Job Card" sub="Guided workshop workflow" onClose={onClose}
      foot={<>
        <Btn variant="ghost" onClick={step ? () => setStep(step-1) : onClose}>{step ? 'Back' : 'Cancel'}</Btn>
        <Btn variant="primary" icon={last?<Icons.check size={16}/>:<Icons.chevR size={16}/>} onClick={last?submit:()=>setStep(step+1)} disabled={busy}>{busy?'Saving…':last?'Close & Notify':'Continue'}</Btn>
      </>}>
      <div className="row" style={{ marginBottom: 22 }}>
        {JOB_STEPS.map((s, ix) => (
          <React.Fragment key={ix}>
            <div style={{ width: 30, height: 30, borderRadius: 50, display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13, flexShrink: 0, background: ix<step?'var(--lime)':ix===step?'var(--ink)':'var(--surface-3)', color: ix<=step?(ix<step?'var(--forest-2)':'#fff'):'var(--ink-3)' }}>
              {ix<step?<Icons.check size={16} stroke={3}/>:ix+1}
            </div>
            {ix < JOB_STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: ix<step?'var(--lime)':'var(--line-2)', margin: '0 4px' }} />}
          </React.Fragment>
        ))}
      </div>
      <div style={{ textAlign: 'center', marginBottom: 18 }}>
        <div style={{ fontWeight: 800, fontSize: 17 }}>{JOB_STEPS[step].t}</div>
        <div className="tiny muted" style={{ marginTop: 3 }}>{JOB_STEPS[step].d}</div>
      </div>

      {step === 0 && <div style={{ display: 'grid', gap: 14 }}>
        <label className="fld"><span>Received From</span>
          <select className="input-block" value={custId} onChange={e => setCustId(e.target.value)}>
            <option value="">— Select customer —</option>
            {customers.map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </label>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>Device</span>
            <select className="input-block" value={deviceId} onChange={e => setDeviceId(e.target.value)}>
              <option value="">— Select device —</option>
              {products.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </label>
          <label className="fld"><span>Serial #</span><input className="input-block mono" value={serial} onChange={e => setSerial(e.target.value)} placeholder="AC10-xxxxx" /></label>
        </div>
      </div>}
      {step === 1 && <div style={{ display: 'grid', gap: 14 }}>
        <label className="fld"><span>Reported Issue</span><textarea className="input-block" rows="2" value={issue} onChange={e => setIssue(e.target.value)} placeholder="e.g. Pressure sensor fault" /></label>
        <label className="fld"><span>Service Type</span><div className="tabs" style={{width:'100%',display:'flex',flexWrap:'wrap'}}>{['Repair','Cleaning','CPAP Titration','Service'].map(t=><button key={t} className={cls('tab', serviceType===t&&'active')} style={{flex:'1 0 40%',fontSize:12.5}} onClick={()=>setServiceType(t)}>{t}</button>)}</div></label>
        <label className="fld"><span>Coverage</span><div className="tabs" style={{width:'100%',display:'flex'}}>{['OEM Warranty','Dynmed Claim','Paid'].map(t=><button key={t} className={cls('tab', claim===t&&'active')} style={{flex:1,fontSize:12.5}} onClick={()=>setClaim(t)}>{t}</button>)}</div></label>
      </div>}
      {step === 2 && <div style={{ display: 'grid', gap: 14 }}>
        <label className="fld"><span>Parts Required</span>
          <select className="input-block" value={selectedPart} onChange={e => setSelectedPart(e.target.value)}>
            <option value="">— Select part —</option>
            {spareParts.map(i=><option key={i.sku||i.id} value={i.name}>{i.name}</option>)}
          </select>
        </label>
        <label className="fld"><span>Hours Logged</span><input className="input-block mono" value={hours} onChange={e => setHours(e.target.value)} placeholder="e.g. 3.5" /></label>
        <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}>
          <Icons.wrench size={18} style={{color:'var(--lime-700)'}}/>
          <span className="tiny" style={{fontWeight:600}}>Parts consumed deduct from inventory automatically.</span>
        </div>
      </div>}
      {step === 3 && <div style={{ background: 'var(--surface-2)', borderRadius: 14, padding: 18 }}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '8px 0' }}><span className="muted">Parts</span><span className="mono" style={{fontWeight:700}}>Rs 24,000</span></div>
        <div className="row" style={{ justifyContent: 'space-between', padding: '8px 0', borderTop: '1px solid var(--line)' }}><span className="muted">Labour (3.5h)</span><span className="mono" style={{fontWeight:700}}>Rs 8,750</span></div>
        <div className="row" style={{ justifyContent: 'space-between', padding: '12px 14px', marginTop: 10, borderRadius: 10, background: 'var(--ink)', color: '#fff' }}><span style={{fontWeight:700}}>Total Bill</span><span className="mono" style={{fontWeight:800}}>Rs 32,750</span></div>
      </div>}
      {step === 4 && <div style={{ textAlign: 'center', padding: '10px 0' }}>
        <div style={{ width: 64, height: 64, borderRadius: 50, background: 'var(--lime-soft)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
          <Icons.check size={34} stroke={2.6} style={{color:'var(--lime-700)'}}/>
        </div>
        <div style={{ fontWeight: 800, fontSize: 18 }}>Job card created</div>
        <div className="tiny muted" style={{ marginTop: 4 }}>Machine received · customer notified.</div>
      </div>}
    </Modal>
  );
}
window.Workshop = Workshop;
