// Patients, Appointments, Waitlist, Notifications, Resources, No-Show, Analytics, Settings, MultiDept

const Patients = ({ onOpenPatient }) => {
  const { PATIENTS, DEPARTMENTS } = window.MOCK;
  const [q, setQ] = useState('');
  const [priority, setPriority] = useState('all');
  const [tag, setTag] = useState('all');

  const filtered = PATIENTS.filter(p => {
    if (q && !p.name.toLowerCase().includes(q.toLowerCase()) && !p.mrn.toLowerCase().includes(q.toLowerCase())) return false;
    if (priority !== 'all' && p.priority !== priority) return false;
    if (tag !== 'all' && !p.tags.includes(tag)) return false;
    return true;
  });

  return (
    <div>
      <div className="filter-bar">
        <div className="search-box" style={{ width: 320 }}>
          <Icon name="search" size={14} />
          <input placeholder="Search by name, MRN…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div className="seg">
          {['all', 'routine', 'standard', 'elevated', 'urgent'].map(p => (
            <button key={p} className={priority === p ? 'active' : ''} onClick={() => setPriority(p)}>{p === 'all' ? 'All priorities' : p}</button>
          ))}
        </div>
        {['all', 'Frequent', 'High no-show', 'Post-op', 'Urgent'].map(t => (
          <button key={t} className={`chip ${tag === t ? 'active' : ''}`} onClick={() => setTag(t)}>{t === 'all' ? 'All tags' : t}</button>
        ))}
        <div style={{ flex: 1 }} />
        <span className="muted" style={{ fontSize: 12 }}>{filtered.length} of {PATIENTS.length}</span>
      </div>
      <div style={{ padding: 20 }}>
        <div className="card">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 36 }}></th>
                <th>Patient</th>
                <th>MRN</th>
                <th>Age / Sex</th>
                <th>Primary condition</th>
                <th>Priority</th>
                <th>No-show risk</th>
                <th>Insurance</th>
                <th>Upcoming</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(p => (
                <tr key={p.id} onClick={() => onOpenPatient(p)}>
                  <td><Avatar name={p.name} size={28} /></td>
                  <td>
                    <div className="prow-name">{p.name}</div>
                    <div className="prow-sub">
                      {p.tags.map(t => <Pill key={t} tone={t === 'Urgent' ? 'err' : t === 'High no-show' ? 'warn' : 'default'} style={{ marginRight: 4 }}>{t}</Pill>)}
                    </div>
                  </td>
                  <td className="mono muted" style={{ fontSize: 12 }}>{p.mrn}</td>
                  <td>{p.age} {p.sex}</td>
                  <td>{p.primaryCondition}</td>
                  <td><PriorityPill priority={p.priority} /></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 48, height: 5, background: 'var(--bg-sub)', borderRadius: 99, overflow: 'hidden' }}>
                        <div style={{ width: `${p.noShowRisk}%`, height: '100%', background: p.noShowRisk > 60 ? 'var(--err)' : p.noShowRisk > 35 ? 'var(--warn)' : 'var(--ok)' }} />
                      </div>
                      <span className="mono" style={{ fontSize: 11 }}>{p.noShowRisk}%</span>
                    </div>
                  </td>
                  <td className="muted" style={{ fontSize: 12 }}>{p.insurance}</td>
                  <td className="mono" style={{ fontSize: 12 }}>{p.upcoming.length}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

const Appointments = ({ onOpenAppt, refreshKey }) => {
  const { APPOINTMENTS, PATIENTS, DOCTORS, ROOMS, DEPARTMENTS, DAYS } = window.MOCK;
  const [q, setQ] = useState('');
  const [status, setStatus] = useState('all');
  const [dept, setDept] = useState('all');
  const [day, setDay] = useState('all');

  // refreshKey in deps forces re-read of APPOINTMENTS when new ones are booked
  const filtered = useMemo(() => APPOINTMENTS.filter(a => {
    const p = PATIENTS.find(x => x.id === a.patientId);
    if (q && !p.name.toLowerCase().includes(q.toLowerCase())) return false;
    if (status !== 'all' && a.status !== status) return false;
    if (dept !== 'all' && a.dept !== dept) return false;
    if (day !== 'all' && a.dayId !== day) return false;
    return true;
  }), [q, status, dept, day, refreshKey]);

  return (
    <div>
      <div className="filter-bar">
        <div className="search-box" style={{ width: 280 }}>
          <Icon name="search" size={14} />
          <input placeholder="Search appointments…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <select className="select" style={{ width: 130 }} value={day} onChange={e => setDay(e.target.value)}>
          <option value="all">All days</option>
          {DAYS.map(d => <option key={d.id} value={d.id}>{d.label} · {d.date}</option>)}
        </select>
        <select className="select" style={{ width: 150 }} value={dept} onChange={e => setDept(e.target.value)}>
          <option value="all">All departments</option>
          {DEPARTMENTS.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
        </select>
        <div className="seg">
          {['all', 'scheduled', 'in-progress', 'completed'].map(s => (
            <button key={s} className={status === s ? 'active' : ''} onClick={() => setStatus(s)}>{s === 'all' ? 'All' : s}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <span className="muted" style={{ fontSize: 12 }}>{filtered.length} appointments</span>
      </div>
      <div style={{ padding: 20 }}>
        <div className="card">
          <table className="tbl">
            <thead>
              <tr>
                <th>Day / time</th>
                <th>Patient</th>
                <th>Service</th>
                <th>Provider</th>
                <th>Dept</th>
                <th>Room</th>
                <th>Duration</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => {
                const p = PATIENTS.find(x => x.id === a.patientId);
                const d = DOCTORS.find(x => x.id === a.docId);
                const r = ROOMS.find(x => x.id === a.roomId);
                const dpt = DEPARTMENTS.find(x => x.id === a.dept);
                const dObj = DAYS.find(x => x.id === a.dayId);
                return (
                  <tr key={a.id} onClick={() => onOpenAppt(a)}>
                    <td>
                      <div className="prow-name">{dObj.label} {dObj.date}</div>
                      <div className="prow-sub mono">{a.startLabel} – {a.endLabel}</div>
                    </td>
                    <td>
                      <div className="prow-name">{p.name}</div>
                      <div className="prow-sub">{p.mrn}</div>
                    </td>
                    <td>{a.typeLabel}{a.chain && <Pill tone="accent" style={{ marginLeft: 6 }}>Chain {a.chain.step}/{a.chain.of}</Pill>}</td>
                    <td>{d.name}</td>
                    <td><Pill><span style={{ width: 6, height: 6, borderRadius: 99, background: dpt.color, display: 'inline-block' }} /> {dpt.name}</Pill></td>
                    <td>{r.name}</td>
                    <td className="mono">{a.duration}m</td>
                    <td><StatusPill status={a.status} /></td>
                    <td><Icon name="chevronRight" size={14} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Patients, Appointments });
