// Five Nodes Hospital — Per-doctor weekly schedule grid
const { useState: useStateD, useEffect: useEffectD, useMemo: useMemoD } = React;

const D_HOURS = Array.from({ length: 13 }, (_, i) => 8 + i);
const D_DAYS_KEYS = ['appts.day.sun','appts.day.mon','appts.day.tue','appts.day.wed','appts.day.thu','appts.day.fri','appts.day.sat'];

function specColorD(code) {
  const s = (window.__data.specialties || []).find(x => x.code === code);
  return s?.color || 'var(--fg-3)';
}

const DoctorSchedule = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  const [doctors, setDoctors] = useStateD([]);
  const [availability, setAvailability] = useStateD([]);
  const [appointments, setAppointments] = useStateD([]);
  const [loading, setLoading] = useStateD(true);
  const [selectedDoc, setSelectedDoc] = useStateD(null);
  const [specialty, setSpecialty] = useStateD('');

  // Load doctors + availability once
  useEffectD(() => {
    let cancelled = false;
    (async () => {
      try {
        const [docs, avail] = await Promise.all([
          window.__api.sbGet('hsp_doctors', { 'select': '*', 'status': 'eq.active', 'order': 'specialty_code.asc,name_en.asc', 'limit': '100' }).catch(() => []),
          window.__api.sbGet('hsp_doctor_availability', { 'select': '*' }).catch(() => [])
        ]);
        if (cancelled) return;
        setDoctors(docs || []);
        setAvailability(avail || []);
        if (docs && docs.length > 0) setSelectedDoc(docs[0].id);
      } catch (e) { console.warn('[schedule]', e.message); }
      finally { if (!cancelled) setLoading(false); }
    })();
    return () => { cancelled = true; };
  }, []);

  // Load this doctor's appointments for current week
  useEffectD(() => {
    if (!selectedDoc) return;
    const today = new Date(); today.setHours(0,0,0,0);
    const sunday = new Date(today); sunday.setDate(sunday.getDate() - sunday.getDay());
    const sat = new Date(sunday); sat.setDate(sat.getDate() + 7);
    let cancelled = false;
    window.__api.sbGet('hsp_appointments', {
      'select':       'id,patient_name,scheduled_for,duration_min,status,specialty_code',
      'doctor_id':    'eq.' + selectedDoc,
      'scheduled_for':'gte.' + sunday.toISOString(),
      'order':        'scheduled_for.asc', 'limit': '200'
    }).then(rows => {
      if (cancelled) return;
      setAppointments((rows || []).filter(r => r.scheduled_for < sat.toISOString()));
    }).catch(e => console.warn('[appts]', e.message));
    return () => { cancelled = true; };
  }, [selectedDoc]);

  const filteredDoctors = useMemoD(() => specialty ? doctors.filter(d => d.specialty_code === specialty) : doctors, [doctors, specialty]);
  const doctor = doctors.find(d => d.id === selectedDoc);
  const docAvail = availability.filter(a => a.doctor_id === selectedDoc);
  const weekStart = useMemoD(() => { const d = new Date(); d.setHours(0,0,0,0); d.setDate(d.getDate() - d.getDay()); return d; }, []);

  const days = useMemoD(() => Array.from({ length: 7 }, (_, i) => { const d = new Date(weekStart); d.setDate(d.getDate() + i); return d; }), [weekStart]);

  return (
    <div className="content view">
      <div className="section-head">
        <div>
          <div className="sub">{t('sched.sub')} {doctors.length} {t('sched.sub.loaded')}</div>
          <h2>{t('sched.title').replace(t('sched.title.em'), '').trim()} <em>{t('sched.title.em')}</em></h2>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="card-body" style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
          <select value={specialty} onChange={e => setSpecialty(e.target.value)}
            style={{ padding: '8px 12px', border: '1px solid var(--line)', borderRadius: 8, background: 'var(--bg-elev)', color: 'var(--fg)', fontSize: 13, fontFamily: 'inherit' }}>
            <option value="">{t('sched.allSpecialties')}</option>
            {window.__data.specialties.map(s => <option key={s.code} value={s.code}>{s.name}</option>)}
          </select>
          <select value={selectedDoc || ''} onChange={e => setSelectedDoc(e.target.value)}
            style={{ flex: 1, minWidth: 280, padding: '8px 12px', border: '1px solid var(--line)', borderRadius: 8, background: 'var(--bg-elev)', color: 'var(--fg)', fontSize: 13, fontFamily: 'inherit' }}>
            {filteredDoctors.map(d => <option key={d.id} value={d.id}>{d.name_en} · {d.specialty_code}</option>)}
          </select>
          {doctor && (
            <div style={{ display: 'flex', gap: 14, fontSize: 12 }}>
              <span><span className="mono" style={{ color: 'var(--fg-3)' }}>{t('sched.fee')}</span> <strong>{doctor.consultation_fee_qar} QAR</strong></span>
              <span><span className="mono" style={{ color: 'var(--fg-3)' }}>{t('sched.exp')}</span> <strong>{doctor.years_experience} {t('sched.exp.yrs')}</strong></span>
              <span><span className="mono" style={{ color: 'var(--fg-3)' }}>{t('sched.lang')}</span> <strong>{(doctor.languages_spoken || []).join(', ')}</strong></span>
            </div>
          )}
        </div>
      </div>

      <div className="card">
        <div className="card-body" style={{ padding: 0, overflowX: 'auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', minWidth: 900 }}>
            <div style={{ padding: '12px 8px', borderBottom: '1px solid var(--line)' }}></div>
            {days.map((d, i) => (
              <div key={i} style={{ padding: '12px 8px', borderBottom: '1px solid var(--line)', borderLeft: '1px solid var(--line)', textAlign: 'center' }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>{t(D_DAYS_KEYS[i])}</div>
                <div style={{ fontSize: 13, fontWeight: 600, marginTop: 2 }}>{d.getDate()}</div>
              </div>
            ))}

            {D_HOURS.map(hour => (
              <React.Fragment key={hour}>
                <div style={{ padding: '4px 8px', borderTop: '1px solid var(--line)', minHeight: 70 }}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)' }}>{String(hour).padStart(2,'0')}:00</div>
                </div>
                {days.map((d, di) => {
                  const dayOfWeek = d.getDay();
                  const matchingAvail = docAvail.filter(a => {
                    if (a.day_of_week !== dayOfWeek) return false;
                    const startH = parseInt(String(a.start_time).split(':')[0]);
                    const endH   = parseInt(String(a.end_time).split(':')[0]);
                    return hour >= startH && hour < endH;
                  });
                  const cellAppts = appointments.filter(a => {
                    const ad = new Date(a.scheduled_for);
                    return ad.toDateString() === d.toDateString() && ad.getHours() === hour;
                  });
                  const isAvailable = matchingAvail.length > 0;
                  return (
                    <div key={di} style={{
                      borderTop: '1px solid var(--line)', borderLeft: '1px solid var(--line)',
                      minHeight: 70, padding: 3,
                      background: isAvailable ? 'var(--accent-soft)' : 'transparent',
                      position: 'relative', display: 'flex', flexDirection: 'column', gap: 2
                    }}>
                      {cellAppts.map((a, ai) => {
                        const ad = new Date(a.scheduled_for);
                        const time = ad.toTimeString().slice(0,5);
                        return (
                          <div key={a.id || ai} title={`${time} · ${a.patient_name}`}
                            style={{ fontSize: 10, padding: '3px 5px', borderRadius: 3, background: 'var(--accent)', color: 'var(--accent-ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {time} {a.patient_name}
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 14, display: 'flex', gap: 16, alignItems: 'center', fontSize: 11, color: 'var(--fg-3)' }}>
        <span className="mono" style={{ textTransform: 'uppercase', letterSpacing: '0.12em' }}>{t('appts.legend')}</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 14, height: 14, background: 'var(--accent-soft)', border: '1px solid var(--accent-line)', borderRadius: 3 }} /> {t('sched.legend.available')}</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 14, height: 14, background: 'var(--accent)', borderRadius: 3 }} /> {t('sched.legend.booked')}</span>
      </div>
    </div>
  );
};

window.DoctorSchedule = DoctorSchedule;
