// Admin pages: Services, Doctors mgmt, Users, Audit log, Settings — wired to real API.

function ServicesPage({ toast }) {
  const [items, setItems] = useState([]);
  const [editing, setEditing] = useState(null);  // {id, name, price}
  const [showNew, setShowNew] = useState(false);
  const [loading, setLoading] = useState(true);

  const reload = () => {
    setLoading(true);
    window.API.listServices({ include_inactive: true })
      .then(rows => { setItems(rows.map(s => ({ ...s, price: Number(s.price) }))); setLoading(false); })
      .catch(err => { toast({ kind: 'danger', title: 'Yuklash xato', msg: err.message }); setLoading(false); });
  };
  useEffect(() => { reload(); }, []);

  const grouped = useMemo(() => groupServicesByCat(items.map(s => ({ ...s, cat: s.category }))), [items]);

  const saveEdit = async () => {
    try {
      await window.API.updateService(editing.id, { name: editing.name, price: Number(editing.price) });
      toast({ kind: 'success', title: 'Saqlandi' });
      setEditing(null);
      reload();
    } catch (err) { toast({ kind: 'danger', title: 'Xato', msg: err.message }); }
  };

  const toggleActive = async (s) => {
    try {
      await window.API.updateService(s.id, { is_active: !s.is_active });
      reload();
    } catch (err) { toast({ kind: 'danger', title: 'Xato', msg: err.message }); }
  };

  const deleteService = async (s) => {
    if (!confirm(`"${s.name}" xizmatini butunlay o'chirmoqchimisiz?\n\nBu amalni qaytarib bo'lmaydi. Agar xizmat qabullarda ishlatilgan bo'lsa, o'chirib bo'lmaydi (avval toggle bilan nofaol qiling).`)) return;
    try {
      await window.API.deleteService(s.id);
      toast({ kind: 'success', title: 'O\'chirildi', msg: s.name });
      reload();
    } catch (err) { toast({ kind: 'danger', title: 'O\'chirib bo\'lmadi', msg: err.message }); }
  };

  return (
    <div className="page-in">
      <PageHeader title="Xizmatlar" sub={`${items.length} ta xizmat narxlari boshqaruvi`}
        actions={<Button variant="primary" icon="plus" onClick={() => setShowNew(true)}>Yangi xizmat</Button>}
      />

      {SERVICE_CATEGORIES.map(cat => (
        <Card key={cat.id} style={{ padding: 0, marginBottom: 16 }}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name={cat.icon} style={{ color: 'var(--brand-primary)' }} />
            <span className="t-h5">{cat.label}</span>
            <Badge tone="neutral" nodot>{(grouped[cat.id] || []).length}</Badge>
          </div>
          <table className="table">
            <thead>
              <tr>
                <th>Nom</th>
                <th className="text-right">Narx</th>
                <th>Holat</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {(grouped[cat.id] || []).map(s => (
                <tr key={s.id}>
                  <td className="td-primary">
                    {editing?.id === s.id ? (
                      <Input value={editing.name} onChange={e => setEditing({ ...editing, name: e.target.value })} />
                    ) : s.name}
                  </td>
                  <td className="text-right">
                    {editing?.id === s.id ? (
                      <Input value={editing.price} style={{ width: 140, marginLeft: 'auto', textAlign: 'right' }}
                        onChange={e => setEditing({ ...editing, price: parseInt(e.target.value.replace(/\D/g,'')) || 0 })} />
                    ) : <span className="td-mono td-primary">{uzMoneyShort(s.price)} so'm</span>}
                  </td>
                  <td>
                    <label className="toggle" onClick={(e) => e.stopPropagation()}>
                      <input type="checkbox" checked={s.is_active} onChange={() => toggleActive(s)} />
                      <span className="toggle__track"></span>
                    </label>
                  </td>
                  <td>
                    <div className="cell-actions">
                      {editing?.id === s.id ? (
                        <>
                          <button className="icon-btn" onClick={saveEdit} title="Saqlash"><Icon name="check" /></button>
                          <button className="icon-btn" onClick={() => setEditing(null)}><Icon name="x" /></button>
                        </>
                      ) : (
                        <>
                          <button className="icon-btn" title="Tahrirlash" onClick={() => setEditing({ id: s.id, name: s.name, price: Number(s.price) })}><Icon name="pencil" /></button>
                          <button className="icon-btn" title="O'chirish" onClick={() => deleteService(s)} style={{ color: 'var(--color-danger)' }}><Icon name="trash" /></button>
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      ))}

      <NewServiceModal open={showNew} onClose={() => setShowNew(false)} onCreated={() => { setShowNew(false); reload(); toast({ kind: 'success', title: "Xizmat qo'shildi" }); }} />
    </div>
  );
}

function NewServiceModal({ open, onClose, onCreated }) {
  const [form, setForm] = useState({ name: '', category: 'dental', price: '' });
  const [saving, setSaving] = useState(false);
  if (!open) return null;

  const save = async () => {
    setSaving(true);
    try {
      await window.API.createService({
        name: form.name.trim(),
        category: form.category,
        price: parseInt(form.price.replace(/\D/g, '')) || 0,
      });
      onCreated();
    } catch (err) {
      alert("Xato: " + err.message);
    } finally { setSaving(false); }
  };

  return (
    <Modal open={open} onClose={onClose} title="Yangi xizmat"
      footer={<>
        <Button variant="ghost" onClick={onClose}>Bekor</Button>
        <Button variant="primary" loading={saving} onClick={save} disabled={!form.name.trim()}>Qo'shish</Button>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Nomi"><Input value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="3D rentgen (panoramik)" autoFocus /></Field>
        <Field label="Kategoriya">
          <Select value={form.category} onChange={e => setForm({...form, category: e.target.value})}>
            {SERVICE_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </Select>
        </Field>
        <Field label="Narxi (so'm)">
          <Input value={form.price} onChange={e => setForm({...form, price: e.target.value})} placeholder="0" />
        </Field>
      </div>
    </Modal>
  );
}

/* =========================================================
   DOCTORS MGMT
   ========================================================= */
function EditDoctorModal({ open, doctor, onClose, onSaved, toast }) {
  const [form, setForm] = useState({ full_name: '', phone: '', specialty: '', clinic: '', telegram_username: '' });
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open || !doctor) return;
    setForm({
      full_name: doctor.full_name || doctor.name || '',
      phone: doctor.phone || '',
      specialty: doctor.specialty || doctor.speciality || '',
      clinic: doctor.clinic || '',
      telegram_username: doctor.telegram_username || doctor.telegram || '',
    });
  }, [open, doctor?.id]);

  const save = async () => {
    if (!form.full_name.trim()) {
      toast?.({ kind: 'warning', title: "F.I.O. talab qilinadi" });
      return;
    }
    setSaving(true);
    try {
      await window.API.updateDoctor(doctor.id, {
        full_name: form.full_name.trim(),
        phone: form.phone.trim() || null,
        specialty: form.specialty.trim() || null,
        clinic: form.clinic.trim() || null,
        telegram_username: form.telegram_username.trim().replace(/^@/, '') || null,
      });
      toast?.({ kind: 'success', title: 'Saqlandi' });
      onSaved?.();
    } catch (err) {
      toast?.({ kind: 'danger', title: 'Saqlash xato', msg: err.message });
    } finally {
      setSaving(false);
    }
  };

  if (!open) return null;
  return (
    <Modal open={open} onClose={onClose} title={`Shifokor tahrirlash`}
      footer={<>
        <Button variant="ghost" onClick={onClose}>Bekor</Button>
        <Button variant="primary" loading={saving} onClick={save}>Saqlash</Button>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="F.I.O.">
          <Input value={form.full_name} onChange={e => setForm({...form, full_name: e.target.value})} autoFocus />
        </Field>
        <Field label="Telefon">
          <Input value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="+998 ..." />
        </Field>
        <Field label="Mutaxassisligi">
          <Input value={form.specialty} onChange={e => setForm({...form, specialty: e.target.value})} placeholder="Stomatolog, LOR, ..." />
        </Field>
        <Field label="Klinika">
          <Input value={form.clinic} onChange={e => setForm({...form, clinic: e.target.value})} placeholder="Klinika nomi" />
        </Field>
        <Field label="Telegram username" hint="@'siz">
          <Input value={form.telegram_username} onChange={e => setForm({...form, telegram_username: e.target.value})} placeholder="username" />
        </Field>
      </div>
    </Modal>
  );
}

function DoctorsPage({ toast }) {
  const [q, setQ] = useState('');
  const [doctors, setDoctors] = useState([]);
  const [showAdd, setShowAdd] = useState(false);
  const [editing, setEditing] = useState(null);

  const me = (window.Auth && window.Auth.getUser && window.Auth.getUser()) || null;
  const canDelete = me && (me.role === 'admin' || me.role === 'super_admin');
  const canEdit = me && (me.role === 'admin' || me.role === 'super_admin' || me.role === 'reception');

  const reload = () => window.API.listDoctors().then(d => setDoctors(d.map(window.normalizeDoctor)));
  useEffect(() => { reload(); }, []);

  const filtered = q ? doctors.filter(d => d.name.toLowerCase().includes(q.toLowerCase())) : doctors;

  // Find doctor full data for editing (passing raw from list response includes specialty etc)
  const startEdit = async (d) => {
    try {
      const all = await window.API.listDoctors();
      const raw = all.find(x => x.id === d.id);
      setEditing(raw || d);
    } catch (err) {
      toast?.({ kind: 'danger', title: 'Yuklash xato', msg: err.message });
    }
  };

  const deleteDoctor = async (d) => {
    if (!confirm(`"${d.name}" shifokorini butunlay o'chirmoqchimisiz?\n\nQabullari shu shifokorga bog'langan bo'lsa — qabullar saqlanadi, lekin shifokor "yo'q" bo'lib qoladi.\n\nAgar shifokor to'lov qabul qilgan bo'lsa, o'chirib bo'lmaydi (foydalanuvchi sahifasida deactivate qiling).`)) return;
    try {
      await window.API.deleteDoctor(d.id);
      toast?.({ kind: 'success', title: "Shifokor o'chirildi", msg: d.name });
      reload();
    } catch (err) {
      toast?.({ kind: 'danger', title: "O'chirib bo'lmadi", msg: err.message });
    }
  };

  return (
    <div className="page-in">
      <PageHeader title="Shifokorlar" sub={`${doctors.length} ta shifokor ro'yxati`}
        actions={<Button variant="primary" icon="plus" onClick={() => setShowAdd(true)}>Yangi shifokor</Button>}
      />
      <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="Shifokor F.I.O..." value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 36 }} />
          </div>
        </div>
        <table className="table">
          <thead><tr><th>F.I.O.</th><th>Mutaxassisligi</th><th>Klinika</th><th>Telefon</th><th>Telegram</th>{(canEdit || canDelete) && <th className="text-right">Amallar</th>}</tr></thead>
          <tbody>
            {filtered.length === 0 && (
              <tr><td colSpan={(canEdit || canDelete) ? 6 : 5} style={{ textAlign: 'center', padding: 24, color: 'var(--fg-4)' }}>Shifokor topilmadi</td></tr>
            )}
            {filtered.map((d) => (
              <tr key={d.id}>
                <td className="td-primary"><div className="row row-3"><Avatar name={d.name} size="sm" /> {d.name}</div></td>
                <td>{d.speciality || '—'}</td>
                <td>{d.clinic || '—'}</td>
                <td className="td-mono">{d.phone || '—'}</td>
                <td>{d.telegram ? <Badge tone="info" icon="paper-plane-tilt">{d.telegram}</Badge> : <span style={{ color: 'var(--fg-4)' }}>—</span>}</td>
                {(canEdit || canDelete) && (
                  <td>
                    <div className="cell-actions">
                      {canEdit && (
                        <button className="icon-btn" title="Tahrirlash" onClick={() => startEdit(d)}><Icon name="pencil" /></button>
                      )}
                      {canDelete && (
                        <button className="icon-btn" title="O'chirish" onClick={() => deleteDoctor(d)} style={{ color: 'var(--color-danger)' }}><Icon name="trash" /></button>
                      )}
                    </div>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <NewDoctorModal open={showAdd} onClose={() => setShowAdd(false)} onCreate={() => { setShowAdd(false); reload(); }} />
      <EditDoctorModal open={!!editing} doctor={editing} toast={toast}
        onClose={() => setEditing(null)}
        onSaved={() => { setEditing(null); reload(); }} />
    </div>
  );
}

/* =========================================================
   USERS
   ========================================================= */
function UsersPage() {
  const [role, setRole] = useState('all');
  const [users, setUsers] = useState([]);

  const reload = () => window.API.listUsers().then(setUsers);
  useEffect(() => { reload(); }, []);

  const filtered = role === 'all' ? users : users.filter(u => u.role === role);

  return (
    <div className="page-in">
      <PageHeader title="Foydalanuvchilar" sub="Tizim foydalanuvchilari va ruxsatlar" />

      <div style={{ marginBottom: 16 }}>
        <Chips items={[
          { id: 'all', label: 'Hammasi', count: users.length },
          { id: 'super_admin', label: 'Super Admin', count: users.filter(u => u.role === 'super_admin').length },
          { id: 'admin', label: 'Admin', count: users.filter(u => u.role === 'admin').length },
          { id: 'reception', label: 'Reception', count: users.filter(u => u.role === 'reception').length },
          { id: 'doctor', label: 'Shifokor', count: users.filter(u => u.role === 'doctor').length },
        ]} value={role} onChange={setRole} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
        {filtered.map(u => (
          <Card key={u.id} hover style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
              <Avatar name={u.full_name} size="xl" />
              <Badge tone={u.is_active ? 'success' : 'neutral'}>{u.is_active ? 'Faol' : 'Nofaol'}</Badge>
            </div>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)' }}>{u.full_name}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', margin: '2px 0 10px' }}>{u.email || u.username}</div>
            <Badge tone={u.role === 'super_admin' ? 'primary' : 'neutral'} nodot>
              <Icon name={
                u.role === 'super_admin' ? 'crown' :
                u.role === 'admin' ? 'shield-check' :
                u.role === 'doctor' ? 'stethoscope' : 'identification-badge'
              } style={{ fontSize: 12 }} />
              {ROLE_LABELS[u.role]}
            </Badge>
          </Card>
        ))}
      </div>
    </div>
  );
}

/* =========================================================
   AUDIT LOG
   ========================================================= */
function AuditPage() {
  const [rows, setRows] = useState([]);
  const [filter, setFilter] = useState('all');

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

  const filtered = filter === 'all' ? rows : rows.filter(a => a.action.startsWith(filter));

  return (
    <div className="page-in">
      <PageHeader title="Audit log" sub="Tizimdagi barcha o'zgarishlar tarixi" />

      <div style={{ marginBottom: 16 }}>
        <Chips items={[
          { id: 'all', label: 'Hammasi' },
          { id: 'visit', label: 'Vizitlar' },
          { id: 'payment', label: "To'lovlar" },
          { id: 'patient', label: 'Bemorlar' },
          { id: 'user', label: 'Foydalanuvchilar' },
          { id: 'service', label: 'Xizmatlar' },
        ]} value={filter} onChange={setFilter} />
      </div>

      <Card style={{ padding: 0 }}>
        {filtered.length === 0 ? (
          <EmptyState art="inbox" title="Hech narsa yo'q" sub="Bu kategoriyada yozuvlar topilmadi" />
        ) : (
          <table className="table">
            <thead><tr><th>Vaqt</th><th>Foydalanuvchi</th><th>Amal</th><th>Entity</th><th>Tafsilot</th></tr></thead>
            <tbody>
              {filtered.map(a => (
                <tr key={a.id}>
                  <td className="td-mono">{uzDateTime(a.created_at)}</td>
                  <td className="td-primary">
                    {a.user ? <div className="row row-3"><Avatar name={a.user.full_name} size="sm" neutral /> {a.user.full_name}</div> : <span style={{ color: 'var(--fg-4)' }}>system</span>}
                  </td>
                  <td><span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--brand-primary)' }}>{a.action}</span></td>
                  <td>{a.entity_type || '—'}</td>
                  <td>{a.description || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
}

/* =========================================================
   SETTINGS
   ========================================================= */
function SettingsPage({ toast }) {
  const [tab, setTab] = useState('general');
  const [settings, setSettings] = useState({});

  useEffect(() => {
    window.API.listSettings().then(rows => {
      const obj = {};
      for (const r of rows) obj[r.key] = r.value || '';
      setSettings(obj);
    }).catch(() => {});
  }, []);

  const update = async (key, value) => {
    try {
      await window.API.updateSetting(key, value);
      setSettings(s => ({ ...s, [key]: value }));
      toast({ kind: 'success', title: 'Saqlandi', msg: key });
    } catch (err) {
      toast({ kind: 'danger', title: 'Xato', msg: err.message });
    }
  };

  const SettingField = ({ k, label, hint, type = 'text' }) => {
    const [v, setV] = useState(settings[k] || '');
    useEffect(() => setV(settings[k] || ''), [settings[k]]);
    return (
      <Field label={label} hint={hint}>
        <div style={{ display: 'flex', gap: 8 }}>
          <Input type={type} value={v} onChange={e => setV(e.target.value)} style={{ flex: 1 }} />
          <Button variant="secondary" size="sm" icon="check" onClick={() => update(k, v)} disabled={v === (settings[k] || '')}>Saqlash</Button>
        </div>
      </Field>
    );
  };

  return (
    <div className="page-in">
      <PageHeader title="Sozlamalar" sub="Tizim va integratsiya sozlamalari" />

      <div style={{ display: 'grid', gridTemplateColumns: '220px minmax(0, 1fr)', gap: 24 }}>
        <Card style={{ padding: 8 }}>
          {[
            { id: 'general', label: 'Umumiy', icon: 'gear' },
            { id: 'telegram', label: 'Telegram', icon: 'paper-plane-tilt' },
            { id: 'watcher', label: 'Watcher', icon: 'eye' },
          ].map(t => (
            <div key={t.id} className={`nav-item ${tab === t.id ? 'is-active' : ''}`} onClick={() => setTab(t.id)}>
              <Icon name={t.icon} className="nav-item__icon" />
              <span className="nav-item__label">{t.label}</span>
            </div>
          ))}
        </Card>

        <div>
          {tab === 'general' && (
            <Card>
              <div className="t-h5" style={{ marginBottom: 16 }}>Umumiy</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <SettingField k="clinic_name" label="Klinika nomi" />
                <SettingField k="currency" label="Valyuta" />
              </div>
            </Card>
          )}

          {tab === 'telegram' && (
            <Card>
              <div className="t-h5" style={{ marginBottom: 16 }}>Telegram bot sozlamalari</div>
              <div style={{ padding: 12, background: 'var(--color-info-soft)', borderRadius: 8, fontSize: 12, color: 'var(--fg-2)', marginBottom: 16, lineHeight: 1.5 }}>
                <strong>4 ta qiymat kerak (300 MB fayl uchun Pyrogram MTProto):</strong><br/>
                1. <strong>Bot token</strong>: <a href="https://t.me/BotFather" target="_blank">@BotFather</a> → <code>/newbot</code><br/>
                2-3. <strong>API ID + Hash</strong>: <a href="https://my.telegram.org/apps" target="_blank">my.telegram.org/apps</a> → "API development tools"<br/>
                4. <strong>Kanal ID</strong>: yopiq kanal yarating, botingizni admin qo'shing
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <SettingField k="telegram_bot_token" label="Bot tokeni" hint="123456:AAH... formati" type="password" />
                <SettingField k="telegram_api_id" label="API ID" hint="my.telegram.org dan, raqam" />
                <SettingField k="telegram_api_hash" label="API hash" hint="my.telegram.org dan, hex string" type="password" />
                <SettingField k="telegram_bot_username" label="Bot username" hint="@your_bot (deep-link uchun)" />
                <SettingField k="telegram_channel_id" label="Kanal / chat ID" hint="-100... formati" />
                <SettingField k="telegram_admin_chat_id" label="Admin chat ID" hint="Xato xabarlari uchun" />
              </div>
            </Card>
          )}

          {tab === 'watcher' && (
            <Card>
              <div className="t-h5" style={{ marginBottom: 16 }}>File Watcher</div>
              <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: '0 0 16px' }}>
                3D rentgen apparati natijalarini avtomatik kuzatish.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <SettingField k="xray_watch_folder" label="Kuzatiladigan papka" hint="To'liq yo'l" />
                <SettingField k="fuzzy_match_threshold" label="Fuzzy match chegarasi" hint="0 — 100, F.I.O. mosligini aniqlash" />
              </div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ServicesPage, DoctorsPage, UsersPage, AuditPage, SettingsPage, NewServiceModal });
