// Doctor-facing pages: Dashboard, My Patients, X-ray detail — wired to API.

function DoctorDashboard({ onNav, me }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;
    window.API.doctorDashboard().then(d => { if (mounted) { setData(d); setLoading(false); } }).catch(() => mounted && setLoading(false));
    return () => { mounted = false; };
  }, []);

  const weekCount = data?.kpis?.week_patients ?? 0;
  const recent = data?.recent || [];
  const telegramLinked = data?.kpis?.telegram_linked;

  // Group by day
  const groupedByDay = {};
  for (const v of recent) {
    const created = new Date(v.created_at);
    const d = uzDate(created);
    const key = d === uzDate(new Date()) ? 'Bugun' : (d === uzDate(new Date(Date.now() - 86400000)) ? 'Kecha' : d);
    (groupedByDay[key] ||= []).push(v);
  }

  const spark1 = makeSpark([3,5,4,7,5,8,4]);
  const spark2 = makeSpark([12,14,11,18,15,22,19]);
  const spark3 = makeSpark([1,2,1,3,2,1,3]);

  return (
    <div className="page-in" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div className="hero-aurora">
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 24, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.16em', color: 'rgba(56,189,248,0.9)', textTransform: 'uppercase', marginBottom: 8 }}>
              {uzDate(new Date())} · Shifokor
            </div>
            <h1 className="hero-aurora__title">Xush kelibsiz, {me?.full_name || 'doktor'}</h1>
            <p className="hero-aurora__sub">{loading ? "Ma'lumot yuklanmoqda..." : `Bu hafta sizga ${weekCount} ta vizit yo'naltirildi.`}</p>
          </div>

          {!telegramLinked ? (
            <Button variant="telegram" size="lg" icon="paper-plane-tilt">Telegram botga ulanish</Button>
          ) : (
            <div style={{ background: 'rgba(56,189,248,0.18)', border: '1px solid rgba(56,189,248,0.3)', borderRadius: 12, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
              <Icon name="paper-plane-tilt" weight="fill" style={{ fontSize: 24, color: '#7DD3FC' }} />
              <div>
                <div style={{ fontSize: 12, color: 'rgba(241,245,249,0.7)' }}>Telegram bot</div>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#fff', fontFamily: 'var(--font-mono)' }}>Ulangan</div>
              </div>
              <span className="badge" style={{ background: 'rgba(18,183,106,0.2)', color: '#34D399' }}>Aktiv</span>
            </div>
          )}
        </div>
      </div>

      <div className="grid-cards-3 anim-stagger">
        <StatCard icon="users-three" label="Bu hafta bemorlar" value={weekCount} delta={18} sparkline={spark2} />
        <StatCard icon="image" iconTone="info" label="Jami rentgenlar" value={recent.length} delta={12} sparkline={spark1} />
        <StatCard icon="chat-circle-dots" iconTone="success" label="Telegram" value={telegramLinked ? 1 : 0} sparkline={spark3} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 320px', gap: 24 }}>
        <Card>
          <div className="row row-between" style={{ marginBottom: 16 }}>
            <div>
              <div className="t-h5">So'nggi bemorlar</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Sizga yo'naltirilgan</div>
            </div>
            <Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => onNav('doctor-patients')}>Hammasini</Button>
          </div>

          {recent.length === 0 ? (
            <EmptyState art="inbox" title="Hozircha vizit yo'q" sub="Reception sizga bemor yo'naltirganda shu yerda ko'rinadi" />
          ) : (
            <div className="timeline">
              {Object.entries(groupedByDay).map(([day, vs]) => (
                <React.Fragment key={day}>
                  <div className="t-eyebrow" style={{ marginBottom: 8, marginLeft: -24, color: 'var(--fg-2)' }}>{day}</div>
                  {vs.map(v => (
                    <div key={v.id} className="tl-item">
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, background: 'var(--surface-2)', borderRadius: 10 }}>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)', width: 48 }}>
                          {new Date(v.created_at).toTimeString().slice(0, 5)}
                        </span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-1)' }}>{v.patient.full_name}</div>
                          <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{uzMoneyShort(v.total_amount)} so'm · <StatusBadge status={v.payment_status} /></div>
                        </div>
                        <button className="icon-btn" title="Ko'rish" onClick={() => onNav('doctor-xray', { visitId: v.id })}><Icon name="arrow-right" /></button>
                      </div>
                    </div>
                  ))}
                </React.Fragment>
              ))}
            </div>
          )}
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card>
            <div className="t-h5" style={{ marginBottom: 12 }}>Telegram bot</div>
            <div style={{ background: 'var(--color-telegram-soft)', borderRadius: 12, padding: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: 'var(--color-telegram)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                  <Icon name="paper-plane-tilt" weight="fill" style={{ fontSize: 20 }} />
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>YourSmile Bot</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>Tez yuklash uchun</div>
                </div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.5 }}>
                Rentgenlarni Telegram orqali tezda oling. Fayl (~300 MB) instant forward qilinadi.
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   DOCTOR — MY PATIENTS
   ========================================================= */
function DoctorPatientsPage({ onNav, toast }) {
  const [q, setQ] = useState('');
  const [page, setPage] = useState(1);
  const [showSentModal, setShowSentModal] = useState(null);
  const [visits, setVisits] = useState([]);

  useEffect(() => {
    window.API.listXrayRecords({ limit: 200 }).then(setVisits).catch(() => {});
  }, []);

  // Group visits by patient (latest per patient)
  const byPatient = new Map();
  for (const v of visits) {
    const existing = byPatient.get(v.patient.id);
    if (!existing || new Date(v.created_at) > new Date(existing.created_at)) {
      byPatient.set(v.patient.id, v);
    }
  }
  let myPatients = Array.from(byPatient.values());
  if (q) myPatients = myPatients.filter(v => v.patient.full_name.toLowerCase().includes(q.toLowerCase()));

  const pageSize = 9;
  const paged = myPatients.slice((page - 1) * pageSize, page * pageSize);

  const handleAction = async (v, kind) => {
    if (kind === 'telegram') {
      setShowSentModal({ v, kind: 'telegram' });
    } else if (kind === 'link') {
      try {
        await window.API.requestLink(v.id);
        toast({ kind: 'success', title: 'Link so\'raldi', msg: 'Reception bildirishnoma oldi' });
      } catch (err) {
        toast({ kind: 'danger', title: 'Xato', msg: err.message });
      }
    }
  };

  return (
    <div className="page-in">
      <PageHeader title="Bemorlarim" sub={`${myPatients.length} ta bemor`} />

      <Card style={{ padding: 0 }}>
        <div className="table-toolbar">
          <div style={{ position: 'relative', width: 320 }}>
            <Icon name="magnifying-glass" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-4)', fontSize: 18 }} />
            <Input placeholder="Bemor F.I.O..." value={q} onChange={e => { setQ(e.target.value); setPage(1); }} style={{ paddingLeft: 36 }} />
          </div>
        </div>

        {paged.length === 0 ? (
          <EmptyState art="patients" title="Bemor topilmadi" sub={q ? "Boshqa qidiruv so'zini sinab ko'ring" : "Sizga yo'naltirilgan bemorlar bu yerda ko'rinadi"} />
        ) : (
          <div style={{ padding: 20, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {paged.map(v => (
              <div key={v.id} className="card card--hover" style={{ padding: 16 }}>
                <div className="row row-3" style={{ marginBottom: 10 }}>
                  <Avatar name={v.patient.full_name} size="lg" />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{highlight(v.patient.full_name, q)}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{v.patient.phone || '—'}</div>
                  </div>
                  <StatusBadge status={v.xray_record?.status || 'pending'} />
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)', padding: '8px 10px', background: 'var(--surface-2)', borderRadius: 8, marginBottom: 10 }}>
                  <div style={{ fontSize: 11, color: 'var(--fg-4)', marginBottom: 2 }}>So'nggi vizit · {uzDate(v.created_at)}</div>
                  <div>{uzMoneyShort(v.total_amount)} so'm</div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Button variant="secondary" size="sm" icon="link" style={{ flex: 1 }} onClick={() => handleAction(v, 'link')}>Link so'rash</Button>
                  <Button variant="telegram" size="sm" icon="paper-plane-tilt" style={{ flex: 1 }} onClick={() => handleAction(v, 'telegram')}>Telegram</Button>
                  <button className="icon-btn" onClick={() => onNav('doctor-xray', { visitId: v.id })}><Icon name="arrow-right" /></button>
                </div>
              </div>
            ))}
          </div>
        )}

        {paged.length > 0 && <Pagination page={page} total={myPatients.length} pageSize={pageSize} onPage={setPage} />}
      </Card>

      {showSentModal && (
        <Modal open={!!showSentModal} onClose={() => setShowSentModal(null)} title="Telegram orqali yuborildi"
          footer={<Button variant="primary" onClick={() => setShowSentModal(null)}>OK</Button>}>
          <div style={{ textAlign: 'center', padding: '12px 0' }}>
            <div style={{ width: 80, height: 80, borderRadius: '50%',
              background: 'var(--color-telegram-soft)', color: 'var(--color-telegram)',
              display: 'grid', placeItems: 'center', margin: '0 auto 16px', fontSize: 36 }}>
              <Icon name="paper-plane-tilt" weight="fill" />
            </div>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>
              {showSentModal.v.patient.full_name} uchun fayl botga yuborildi
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>
              Telegram'da botingizdan tekshiring (~300 MB instant forward)
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* =========================================================
   DOCTOR — X-RAY DETAIL
   ========================================================= */
function DoctorXrayPage({ onNav, visitId, toast }) {
  const [visit, setVisit] = useState(null);

  useEffect(() => {
    if (!visitId) return;
    window.API.getVisit(visitId).then(setVisit).catch(() => {});
  }, [visitId]);

  if (!visit) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>Yuklanmoqda...</div>;

  const requestLink = async () => {
    try {
      await window.API.requestLink(visit.id);
      toast({ kind: 'success', title: 'Link so\'raldi', msg: 'Reception bildirishnoma oldi' });
    } catch (err) {
      toast({ kind: 'danger', title: 'Xato', msg: err.message });
    }
  };

  return (
    <div className="page-in">
      <PageHeader
        title={`Rentgen — ${visit.patient.full_name}`}
        sub={uzDateTime(visit.created_at)}
        breadcrumbs={[<a href="#" onClick={() => onNav('doctor-patients')} key="b">Bemorlarim</a>, visit.patient.full_name]}
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 320px', gap: 24 }}>
        <Card>
          <XrayPreview3D />

          <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
            {visit.xray_record?.external_link ? (
              <a href={visit.xray_record.external_link} target="_blank" rel="noopener noreferrer" className="btn btn--primary btn--lg" style={{ flex: 1 }}>
                <Icon name="cube" /> 3D viewer ochish
              </a>
            ) : (
              <Button variant="secondary" size="lg" icon="link" style={{ flex: 1 }} onClick={requestLink}>
                3D viewer link so'rash
              </Button>
            )}
            <Button variant="telegram" size="lg" icon="paper-plane-tilt" style={{ flex: 1 }}>
              Telegram'da olish
            </Button>
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card>
            <div className="t-h5" style={{ marginBottom: 12 }}>Bemor</div>
            <div className="row row-3" style={{ marginBottom: 14 }}>
              <Avatar name={visit.patient.full_name} size="lg" />
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{visit.patient.full_name}</div>
                {visit.patient.birth_date && <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{age(new Date(visit.patient.birth_date))} yosh</div>}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {visit.patient.phone && <InfoRow icon="phone" label="Telefon" value={visit.patient.phone} />}
              {visit.patient.birth_date && <InfoRow icon="calendar" label="Tug'ilgan" value={uzDate(new Date(visit.patient.birth_date))} />}
            </div>
          </Card>

          <Card>
            <div className="t-h5" style={{ marginBottom: 12 }}>Xizmatlar</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {visit.items?.map(item => (
                <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 12px', background: 'var(--surface-2)', borderRadius: 8, fontSize: 13 }}>
                  <span style={{ color: 'var(--fg-1)' }}>{item.service.name}</span>
                  <span style={{ color: 'var(--fg-3)', fontVariantNumeric: 'tabular-nums' }}>{uzMoneyShort(item.price_at_moment)}</span>
                </div>
              ))}
            </div>
            <div style={{ borderTop: '1px solid var(--border-2)', marginTop: 12, paddingTop: 12, display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>Jami</span>
              <span style={{ fontSize: 16, fontWeight: 700 }}>{uzMoneyShort(visit.total_amount)} so'm</span>
            </div>
          </Card>

          <Card>
            <div className="t-h5" style={{ marginBottom: 12 }}>Holat</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
              <div className="row row-between"><span style={{ color: 'var(--fg-3)' }}>Fayl</span><StatusBadge status={visit.xray_record?.status || 'pending'} /></div>
              <div className="row row-between"><span style={{ color: 'var(--fg-3)' }}>To'lov</span><StatusBadge status={visit.payment_status} /></div>
              <div className="row row-between"><span style={{ color: 'var(--fg-3)' }}>3D viewer link</span>{visit.xray_record?.external_link ? <Badge tone="success">Bor</Badge> : <Badge tone="warning">Yo'q</Badge>}</div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DoctorDashboard, DoctorPatientsPage, DoctorXrayPage });
