/* ============================================================
   ELECTROMED — Sleep Tests (booked within Sales)
   Appointment → Charges & Advance → Study → Report
   ============================================================ */
function SleepTests({ branch }) {
  const { PKR } = window.DATA;
  const [tab, setTab] = useState('All');
  const [q, setQ]     = useState('');
  const [sel, setSel] = useState(null);
  const [neu, setNeu] = useState(false);

  const { data: tests, loading, refetch } = useSleepTests();

  const list = tests.filter((t) =>
    (branch === 'All' || t.branch === branch) &&
    (tab === 'All' || t.status === tab) &&
    (t.no.toLowerCase().includes(q.toLowerCase()) || t.patient.toLowerCase().includes(q.toLowerCase()))
  );

  const billed  = tests.reduce((s, t) => s + Number(t.charges), 0);
  const advance = tests.reduce((s, t) => s + Number(t.advance), 0);

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.moon size={18} />} label="Upcoming Studies" value={tests.filter(t => t.status === 'Scheduled').length} sub="scheduled" />
        <StatCard icon={<Icons.doc size={18} />} label="Reports Ready" value={tests.filter(t => t.report).length} sub="diagnosed" />
        <StatCard icon={<Icons.pay size={18} />} label="Test Charges" value={PKR(billed)} />
        <StatCard icon={<Icons.clock size={18} />} label="Advance Received" value={PKR(advance)} accent />
      </div>

      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <Tabs tabs={['All', 'Scheduled', 'In Progress', 'Reported']} value={tab} onChange={setTab} />
          <div className="row" style={{ gap: 10 }}>
            <SearchBox value={q} onChange={setQ} placeholder="Test or patient…" w={220} />
            {window.can('sleep_tests','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setNeu(true)}>Book Sleep Test</Btn>}
          </div>
        </div>
        <div style={{ overflowX: 'auto' }}>
          {loading ? <div className="ph-img" style={{ height: 110, margin: 18 }}>Loading…</div> : (
            <table className="tbl">
              <thead><tr><th>Test</th><th>Patient</th><th>Study Type</th><th>Ref. Doctor</th><th>Appointment</th><th>Charges</th><th>Balance</th><th>Status</th></tr></thead>
              <tbody>
                {list.map((t) => {
                  const bal = Number(t.charges) - Number(t.advance);
                  return (
                    <tr key={t.id} style={{ cursor: 'pointer' }} onClick={() => setSel(t)}>
                      <td className="mono" style={{ fontWeight: 700 }}>{t.no}</td>
                      <td style={{ fontWeight: 600 }}>{t.patient}</td>
                      <td className="muted">{t.type}</td>
                      <td className="tiny">{t.doctor}</td>
                      <td className="tiny muted">{t.date}{t.time && t.time !== '—' && <><br />{t.time}</>}</td>
                      <td className="mono" style={{ fontWeight: 700 }}>{PKR(Number(t.charges))}</td>
                      <td className="mono" style={{ color: bal > 0 ? 'var(--bad)' : 'var(--ok)', fontWeight: 600 }}>{bal > 0 ? PKR(bal) : 'Clear'}</td>
                      <td><Badge kind={window.statusKind(t.status)}>{t.status}</Badge></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
        {!loading && !list.length && <div className="ph-img" style={{ height: 110, margin: 18 }}>no sleep tests match</div>}
      </div>

      {sel && <SleepDetail t={sel} onClose={() => setSel(null)} onUpdate={refetch} />}
      {neu && <NewSleepTest onClose={() => setNeu(false)} onCreated={refetch} />}
    </div>
  );
}

function SleepDetail({ t, onClose, onUpdate }) {
  const { PKR } = window.DATA;
  const bal = Number(t.charges) - Number(t.advance);
  const ahi = Number(t.ahi) || 0;
  const sev = ahi >= 30 ? ['Severe', 'var(--bad)', 'var(--bad-bg)'] : ahi >= 15 ? ['Moderate', 'var(--warn)', 'var(--warn-bg)'] : ['Mild', 'var(--ok)', 'var(--ok-bg)'];
  return (
    <Modal wide title={`Sleep Test ${t.no}`} sub={`${t.patient} · ${t.type}`} onClose={onClose}
      foot={<>
        <Btn variant="ghost" icon={<Icons.print size={16} />}>Print</Btn>
        {bal > 0 && <Btn variant="dark" icon={<Icons.pay size={16} />}>Collect Balance</Btn>}
        {t.report ? <Btn variant="primary" icon={<Icons.doc size={16} />}>Download Report</Btn> : <Btn variant="primary" icon={<Icons.check size={16} />}>Upload Report</Btn>}
      </>}>
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
        {[['Study Type', t.type], ['Referring Doctor', t.doctor], ['Appointment', t.date + (t.time && t.time !== '—' ? ' · ' + t.time : '')], ['Technician / Branch', `${t.tech} · ${t.branch}`]].map(([k, v]) => (
          <div key={k} style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}>
            <div className="tiny muted" style={{ fontWeight: 700 }}>{k}</div>
            <div style={{ fontWeight: 700, marginTop: 3 }}>{v}</div>
          </div>
        ))}
      </div>

      <div className="row" style={{ gap: 12, marginBottom: 16 }}>
        <div className="grow" style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}><div className="tiny muted" style={{ fontWeight: 700 }}>Test Charges</div><div className="mono" style={{ fontWeight: 800, marginTop: 3 }}>{PKR(Number(t.charges))}</div></div>
        <div className="grow" style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}><div className="tiny muted" style={{ fontWeight: 700 }}>Advance Received</div><div className="mono" style={{ fontWeight: 800, marginTop: 3 }}>{PKR(Number(t.advance))}</div></div>
        <div className="grow" style={{ background: bal > 0 ? 'var(--bad-bg)' : 'var(--ok-bg)', borderRadius: 12, padding: '12px 14px' }}><div className="tiny" style={{ fontWeight: 700, color: bal > 0 ? 'var(--bad)' : 'var(--ok)' }}>Balance</div><div className="mono" style={{ fontWeight: 800, marginTop: 3, color: bal > 0 ? 'var(--bad)' : 'var(--ok)' }}>{bal > 0 ? PKR(bal) : 'Paid'}</div></div>
      </div>

      {t.report ? (
        <div style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
          <div className="row" style={{ justifyContent: 'space-between', padding: '14px 18px', background: 'var(--grad-green)', color: '#fff' }}>
            <span className="row" style={{ gap: 9, fontWeight: 800 }}><Icons.doc size={18} />Diagnostic Report</span>
            <Badge kind="ok">Finalised</Badge>
          </div>
          <div style={{ padding: 18 }}>
            <div className="row" style={{ gap: 12, marginBottom: 14 }}>
              <div className="grow" style={{ textAlign: 'center', background: 'var(--surface-2)', borderRadius: 12, padding: '14px 10px' }}><div style={{ fontWeight: 800, fontSize: 24 }} className="mono">{t.ahi}</div><div className="tiny muted">AHI (events/hr)</div></div>
              <div className="grow" style={{ textAlign: 'center', background: 'var(--surface-2)', borderRadius: 12, padding: '14px 10px' }}><div style={{ fontWeight: 800, fontSize: 24 }} className="mono">{t.spo2}%</div><div className="tiny muted">Min. SpO₂</div></div>
              <div className="grow" style={{ textAlign: 'center', background: sev[2], borderRadius: 12, padding: '14px 10px' }}><div style={{ fontWeight: 800, fontSize: 16, color: sev[1], marginTop: 5 }}>{sev[0]}</div><div className="tiny" style={{ color: sev[1] }}>Severity</div></div>
            </div>
            <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px', marginBottom: 10 }}><div className="tiny muted" style={{ fontWeight: 700 }}>Diagnosis</div><div style={{ fontWeight: 700, marginTop: 3 }}>{t.diagnosis}</div></div>
            <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--lime-soft)', borderRadius: 12 }}><Icons.bolt size={18} style={{ color: 'var(--lime-700)', flexShrink: 0 }} /><div><div className="tiny muted" style={{ fontWeight: 700 }}>Recommendation</div><div style={{ fontWeight: 700, marginTop: 2 }}>{t.recommend}</div></div></div>
          </div>
        </div>
      ) : (
        <div className="row" style={{ gap: 10, padding: '14px 16px', borderRadius: 12, background: 'var(--warn-bg)' }}>
          <Icons.clock size={20} style={{ color: 'var(--warn)' }} />
          <div><div style={{ fontWeight: 700, color: 'var(--warn)' }}>Report pending</div><div className="tiny muted">{t.status === 'In Progress' ? 'Study in progress — report will be uploaded once scoring is complete.' : 'Awaiting the scheduled study. A reminder is sent to the patient 1 day prior.'}</div></div>
        </div>
      )}
    </Modal>
  );
}

function NewSleepTest({ onClose, onCreated }) {
  const D = window.DATA;
  const today = new Date().toISOString().slice(0, 10);
  const { data: customers }   = useCustomers();
  const { data: doctors   }   = useDoctors();
  const { data: users     }   = useUsers();
  const { data: studyTypes, loading: typesLoading } = useStudyTypes();

  const individuals = customers.filter(c => (c.type || c.customer_type) === 'Individual');

  const [patient,  setPatient]  = useState('');
  const [custId,   setCustId]   = useState('');
  const [type,     setType]     = useState('');
  const [doctor,   setDoctor]   = useState('');
  const [date,     setDate]     = useState(today);
  const [time,     setTime]     = useState('21:00');
  const [charges,  setCharges]  = useState('');
  const [advance,  setAdvance]  = useState('');
  const [tech,     setTech]     = useState('');
  const [branch,   setBranch]   = useState('');
  const [saving,   setSaving]   = useState(false);
  const [err,      setErr]      = useState('');

  // Initialise defaults once data loads
  React.useEffect(() => {
    if (individuals.length && !patient) { setPatient(individuals[0].name); setCustId(individuals[0].id); }
  }, [individuals.length]);
  React.useEffect(() => { if (doctors.length && !doctor) setDoctor(doctors[0].name); }, [doctors.length]);
  React.useEffect(() => {
    if (users.length && !tech) {
      const u = users[0]; setTech(`${u.name} (${u.branch_id || 'HQ'})`); setBranch(u.branch_id || 'HQ');
    }
  }, [users.length]);
  React.useEffect(() => {
    if (studyTypes.length && !type) {
      setType(studyTypes[0].name);
      setCharges(studyTypes[0].default_charge);
    }
  }, [studyTypes.length]);

  function handlePatientChange(e) {
    const name = e.target.value;
    setPatient(name);
    const c = customers.find(c => c.name === name);
    setCustId(c?.id || '');
  }

  function handleTechChange(e) {
    const val = e.target.value;
    setTech(val);
    const u = users.find(u => `${u.name} (${u.branch_id || 'HQ'})` === val);
    setBranch(u?.branch_id || '');
  }

  function handleTypeClick(st) {
    setType(st.name);
    setCharges(st.default_charge);
  }

  async function handleBook() {
    if (!patient) { setErr('Patient is required.'); return; }
    if (!date)    { setErr('Date is required.'); return; }
    setSaving(true);
    setErr('');
    try {
      await api.createSleepTest({
        customer_id: custId || null,
        patient,
        doctor,
        type,
        date,
        time: time || '—',
        charges: Number(charges) || 0,
        advance: advance ? Number(advance) : 0,
        branch,
        tech: tech.replace(/\s*\(.*\)$/, ''),
        status: 'Scheduled',
        report: 0,
      });
      onCreated();
      onClose();
    } catch (e) {
      setErr(e.message || 'Failed to book sleep test.');
      setSaving(false);
    }
  }

  return (
    <Modal title="Book Sleep Test" sub="Schedule a diagnostic study" onClose={onClose}
      foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon={<Icons.check size={16} />} onClick={handleBook} disabled={saving}>{saving ? 'Booking…' : 'Book & Notify'}</Btn></>}>
      <div style={{ display: 'grid', gap: 14 }}>
        {err && <div style={{ color: 'var(--bad)', background: 'var(--bad-bg)', borderRadius: 10, padding: '10px 14px', fontSize: 13 }}>{err}</div>}
        <label className="fld"><span>Patient</span>
          <select className="input-block" value={patient} onChange={handlePatientChange}>
            <option value="">— Select patient —</option>
            {individuals.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
          </select>
        </label>
        <label className="fld"><span>Study Type</span>
          {typesLoading ? <div className="input-block" style={{ color: 'var(--ink-3)' }}>Loading types…</div> : (
            <div className="tabs" style={{ width: '100%', display: 'flex', flexWrap: 'wrap' }}>
              {studyTypes.map(st => (
                <button key={st.id} className={cls('tab', type === st.name && 'active')} style={{ flex: '1 0 45%', fontSize: 12 }} onClick={() => handleTypeClick(st)}>{st.name}</button>
              ))}
            </div>
          )}
        </label>
        <label className="fld"><span>Referring Doctor</span>
          <select className="input-block" value={doctor} onChange={(e) => setDoctor(e.target.value)}>
            <option value="">— None —</option>
            {doctors.map(d => <option key={d.id} value={d.name}>{d.name}</option>)}
          </select>
        </label>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>Date</span><input type="date" className="input-block" value={date} onChange={(e) => setDate(e.target.value)} /></label>
          <label className="fld"><span>Time</span><input type="time" className="input-block" value={time} onChange={(e) => setTime(e.target.value)} /></label>
        </div>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>Test Charges (Rs)</span><input className="input-block mono" value={charges} onChange={(e) => setCharges(e.target.value.replace(/[^0-9]/g, ''))} placeholder="0" /></label>
          <label className="fld"><span>Advance Received (Rs)</span><input className="input-block mono" placeholder="0" value={advance} onChange={(e) => setAdvance(e.target.value.replace(/[^0-9]/g, ''))} /></label>
        </div>
        <label className="fld"><span>Technician / Branch</span>
          <select className="input-block" value={tech} onChange={handleTechChange}>
            <option value="">— Select technician —</option>
            {users.map(u => <option key={u.id} value={`${u.name} (${u.branch_id || 'HQ'})`}>{u.name} ({u.branch_id || 'HQ'})</option>)}
          </select>
        </label>
      </div>
    </Modal>
  );
}

window.SleepTests = SleepTests;
