// Kassa: Records, Debts. Plus Reports. — Wired to real API.

// LOKAL sana (UTC emas) — hisobot backend'da klinika mahalliy kuni sifatida talqin qilinadi.
// toISOString() UTC beradi: mahalliy 00:00–05:00 da kechagi kun chiqib, hisobot noto'g'ri kunni olardi.
function localISO(d) {
  const pad = n => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
function todayISO() {
  return localISO(new Date());
}
function daysAgoISO(n) {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return localISO(d);
}

function KassaPage({ onNav, toast }) {
  const [dateRange, setDateRange] = useState('today');
  const [doctorFilter, setDoctorFilter] = useState([]);
  const [statusFilter, setStatusFilter] = useState([]);
  const [page, setPage] = useState(1);
  const pageSize = 12;

  const [visits, setVisits] = useState([]);
  const [doctors, setDoctors] = useState([]);
  const [summary, setSummary] = useState(null);
  const [loading, setLoading] = useState(true);

  const queryArgs = useMemo(() => {
    const t = new Date();
    let date_from, date_to;
    const todayStart = new Date(t); todayStart.setHours(0,0,0,0);
    if (dateRange === 'today') {
      date_from = todayStart.toISOString();
    } else if (dateRange === 'yesterday') {
      const ys = new Date(todayStart); ys.setDate(ys.getDate() - 1);
      const ye = new Date(todayStart);
      date_from = ys.toISOString();
      date_to = ye.toISOString();
    } else if (dateRange === 'week') {
      const ws = new Date(todayStart); ws.setDate(ws.getDate() - 7);
      date_from = ws.toISOString();
    } else if (dateRange === 'month') {
      const ms = new Date(todayStart); ms.setMonth(ms.getMonth() - 1);
      date_from = ms.toISOString();
    }
    const doctor_id = doctorFilter[0] || null;
    const payment_status = statusFilter.length === 1 ? statusFilter[0] : null;
    return { date_from, date_to, doctor_id, payment_status };
  }, [dateRange, doctorFilter, statusFilter]);

  useEffect(() => {
    let mounted = true;
    window.API.listDoctors().then(d => { if (mounted) setDoctors(d.map(window.normalizeDoctor)); });
    return () => { mounted = false; };
  }, []);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    Promise.all([
      window.API.listKassa({ ...queryArgs, limit: 500 }),
      window.API.kassaSummary(queryArgs),
    ]).then(([v, s]) => {
      if (!mounted) return;
      // multi-status filter — client side
      let filtered = v;
      if (statusFilter.length > 1) {
        filtered = v.filter(x => statusFilter.includes(x.payment_status));
      }
      setVisits(filtered);
      setSummary(s);
    }).catch(err => toast({ kind: 'danger', title: 'Yuklash xato', msg: err.message }))
      .finally(() => mounted && setLoading(false));
    return () => { mounted = false; };
  }, [queryArgs, statusFilter, toast]);

  const totals = {
    total: summary?.total_amount ?? 0,
    paid: summary?.paid_amount ?? 0,
    debt: summary?.debt_amount ?? 0,
    count: summary?.visits_count ?? visits.length,
  };

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

  const handleExcelDownload = async () => {
    try {
      if (dateRange === 'today') {
        await window.API.downloadDaily(todayISO());
      } else {
        // period
        const from = queryArgs.date_from ? queryArgs.date_from.slice(0, 10) : daysAgoISO(7);
        const to = todayISO();
        await window.API.downloadPeriod(from, to);
      }
      toast({ kind: 'success', title: 'Hisobot yuklab olindi' });
    } catch (err) {
      toast({ kind: 'danger', title: 'Excel xato', msg: err.message });
    }
  };

  return (
    <div className="page-in">
      <PageHeader title="Kassa — Yozuvlar" sub="Vizitlar va to'lovlar tarixi"
        actions={
          <>
            <Button variant="secondary" icon="export" onClick={handleExcelDownload}>Excel yuklab olish</Button>
            <Button variant="primary" icon="plus-circle" onClick={() => onNav('new-visit')}>Yangi vizit</Button>
          </>
        }
      />

      {/* Filters */}
      <Card style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center' }}>
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 6 }}>Davr</div>
            <Chips items={[
              { id: 'today', label: 'Bugun' },
              { id: 'yesterday', label: 'Kecha' },
              { id: 'week', label: 'Bu hafta' },
              { id: 'month', label: 'Bu oy' },
              { id: 'all', label: 'Hammasi' },
            ]} value={dateRange} onChange={setDateRange} />
          </div>
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 6 }}>Holat</div>
            <Chips multi items={[
              { id: 'paid', label: "To'landi" },
              { id: 'partial', label: 'Qisman' },
              { id: 'unpaid', label: 'Qarz' },
            ]} value={statusFilter} onChange={setStatusFilter} />
          </div>
          <div style={{ marginLeft: 'auto' }}>
            <div className="t-eyebrow" style={{ marginBottom: 6 }}>Shifokor</div>
            <Select value={doctorFilter[0] || ''} onChange={e => setDoctorFilter(e.target.value ? [+e.target.value] : [])} style={{ minWidth: 200 }}>
              <option value="">Hamma shifokorlar</option>
              {doctors.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
            </Select>
          </div>
        </div>
      </Card>

      {/* Totals */}
      <div className="grid-cards-4" style={{ marginBottom: 16 }}>
        <StatCard icon="hash" label="Jami vizitlar" value={totals.count} />
        <StatCard icon="money" iconTone="" label="Umumiy summa" value={Number(totals.total)} format={uzMoneyShort} />
        <StatCard icon="check-circle" iconTone="success" label="To'landi" value={Number(totals.paid)} format={uzMoneyShort} />
        <StatCard icon="warning" iconTone="warning" label="Qarz" value={Number(totals.debt)} format={uzMoneyShort} />
      </div>

      {/* Table */}
      <Card style={{ padding: 0 }}>
        {!loading && paged.length === 0 ? (
          <EmptyState art="inbox" title="Yozuv topilmadi" sub="Filtrlarni bo'shatib ko'ring" />
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>Sana</th>
                <th>Bemor</th>
                <th>Shifokor</th>
                <th className="text-right">Jami</th>
                <th>To'lov</th>
                <th>Holat</th>
              </tr>
            </thead>
            <tbody>
              {paged.map(v => (
                <tr key={v.id} onClick={() => onNav('patient-detail', { patientId: v.patient.id })}>
                  <td className="td-mono">{uzDateTime(v.created_at)}</td>
                  <td className="td-primary">{v.patient.full_name}</td>
                  <td>{v.doctor?.full_name || <span style={{ color: 'var(--fg-4)' }}>—</span>}</td>
                  <td className="text-right td-primary">{uzMoneyShort(v.total_amount)}</td>
                  <td><PayTypeBadge type={v.payment_method || 'debt'} /></td>
                  <td><StatusBadge status={v.payment_status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {paged.length > 0 && <Pagination page={page} total={visits.length} pageSize={pageSize} onPage={setPage} />}
      </Card>
    </div>
  );
}

/* =========================================================
   DEBTS
   ========================================================= */
function DebtsPage({ onNav, toast }) {
  const [debts, setDebts] = useState([]);
  const [paymentModal, setPaymentModal] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = () => {
    setLoading(true);
    window.API.listDebts({ limit: 500 })
      .then(d => setDebts(d))
      .catch(err => toast({ kind: 'danger', title: 'Xato', msg: err.message }))
      .finally(() => setLoading(false));
  };
  useEffect(() => { load(); }, []);

  const totalDebt = debts.reduce((s, v) => s + (Number(v.total_amount) - Number(v.paid_amount)), 0);

  const handlePayment = async (amount, method) => {
    try {
      await window.API.addPayment(paymentModal.id, { amount, method });
      toast({ kind: 'success', title: "To'lov qabul qilindi", msg: `${uzMoney(amount)} — ${paymentModal.patient.full_name}` });
      setPaymentModal(null);
      load();
    } catch (err) {
      toast({ kind: 'danger', title: 'Xato', msg: err.message });
    }
  };

  return (
    <div className="page-in">
      <PageHeader title="Qarzlar" sub={`Jami ${debts.length} ta qarzdor · ${uzMoney(totalDebt)}`} />

      {debts.length > 0 && (
        <div style={{
          background: 'linear-gradient(135deg, rgba(247,144,9,0.1), rgba(240,68,56,0.05))',
          border: '1px solid var(--color-warning-soft)',
          borderRadius: 14, padding: 18, marginBottom: 16,
          display: 'flex', alignItems: 'center', gap: 16,
        }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--color-warning-soft)', color: 'var(--color-warning)', display: 'grid', placeItems: 'center' }}>
            <Icon name="warning" weight="fill" style={{ fontSize: 24 }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>{debts.length} ta bemorda qarz mavjud</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Jami summa: {uzMoney(totalDebt)}</div>
          </div>
        </div>
      )}

      <Card style={{ padding: 0 }}>
        {!loading && debts.length === 0 ? (
          <EmptyState art="debt" title="Qarz yo'q" sub="Barcha to'lovlar to'liq amalga oshirilgan" />
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>Bemor</th>
                <th>Telefon</th>
                <th>Sana</th>
                <th className="text-right">Jami</th>
                <th className="text-right">To'langan</th>
                <th className="text-right">Qarz</th>
                <th>Vaqt</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {debts.map(v => {
                const debt = Number(v.total_amount) - Number(v.paid_amount);
                const daysAgo = Math.floor((Date.now() - new Date(v.created_at).getTime()) / 86400000);
                return (
                  <tr key={v.id}>
                    <td className="td-primary">
                      <div className="row row-3">
                        <Avatar name={v.patient.full_name} size="sm" neutral />
                        {v.patient.full_name}
                      </div>
                    </td>
                    <td className="td-mono">{v.patient.phone || '—'}</td>
                    <td>{uzDate(v.created_at)}</td>
                    <td className="text-right td-mono">{uzMoneyShort(v.total_amount)}</td>
                    <td className="text-right td-mono" style={{ color: 'var(--color-success)' }}>{uzMoneyShort(v.paid_amount)}</td>
                    <td className="text-right td-mono" style={{ color: 'var(--color-danger)', fontWeight: 600 }}>{uzMoneyShort(debt)}</td>
                    <td>
                      <Badge tone={daysAgo > 7 ? 'danger' : daysAgo > 3 ? 'warning' : 'neutral'}>{daysAgo > 0 ? `${daysAgo} kun` : 'Bugun'}</Badge>
                    </td>
                    <td onClick={e => e.stopPropagation()}>
                      <Button variant="primary" size="sm" icon="plus" onClick={() => setPaymentModal({ ...v, _debt: debt })}>To'lov</Button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </Card>

      {paymentModal && (
        <PaymentModal visit={paymentModal} onClose={() => setPaymentModal(null)} onSubmit={handlePayment} />
      )}
    </div>
  );
}

function PaymentModal({ visit, onClose, onSubmit }) {
  const debt = Number(visit._debt ?? (Number(visit.total_amount) - Number(visit.paid_amount)));
  const [amount, setAmount] = useState(debt);
  const [type, setType] = useState('cash');
  const [submitting, setSubmitting] = useState(false);

  const valid = amount > 0 && amount <= debt;
  const errorMsg = amount <= 0 ? "Summa noldan katta bo'lishi kerak"
                 : amount > debt ? `Qoldiq qarzdan (${uzMoneyShort(debt)}) oshmasligi kerak`
                 : null;

  const handle = async () => {
    if (!valid) return;
    setSubmitting(true);
    try { await onSubmit(amount, type); }
    finally { setSubmitting(false); }
  };

  return (
    <Modal open={!!visit} onClose={onClose} title="To'lov qabul qilish"
      footer={<>
        <Button variant="ghost" onClick={onClose}>Bekor qilish</Button>
        <Button variant="primary" icon="check" loading={submitting} disabled={!valid} onClick={handle}>Qabul qilish</Button>
      </>}>
      <div style={{ background: 'var(--surface-2)', padding: 14, borderRadius: 10, marginBottom: 16 }}>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 4 }}>Bemor</div>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 8 }}>{visit.patient.full_name}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, fontSize: 12 }}>
          <div><div style={{ color: 'var(--fg-3)' }}>Jami</div><div style={{ fontWeight: 600 }}>{uzMoneyShort(visit.total_amount)}</div></div>
          <div><div style={{ color: 'var(--fg-3)' }}>To'landi</div><div style={{ fontWeight: 600, color: 'var(--color-success)' }}>{uzMoneyShort(visit.paid_amount)}</div></div>
          <div><div style={{ color: 'var(--fg-3)' }}>Qarz</div><div style={{ fontWeight: 600, color: 'var(--color-danger)' }}>{uzMoneyShort(debt)}</div></div>
        </div>
      </div>
      <Field label="Summa">
        <Input value={amount} onChange={e => setAmount(parseInt(e.target.value.replace(/\D/g,'')) || 0)} />
        {errorMsg && (
          <div style={{ fontSize: 12, color: 'var(--color-danger)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="warning" style={{ fontSize: 13 }} />{errorMsg}
          </div>
        )}
      </Field>
      <div style={{ marginTop: 14 }}>
        <div className="t-eyebrow" style={{ marginBottom: 8 }}>To'lov turi</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
          {[{id:'cash',l:'Naqd',i:'money'},{id:'card',l:'Karta',i:'credit-card'},{id:'transfer',l:"O'tkazma",i:'arrows-left-right'}].map(t => (
            <button key={t.id} className={`svc-card ${type === t.id ? 'is-selected' : ''}`}
              style={{ padding: 12, flexDirection: 'column', gap: 6, justifyContent: 'center', textAlign: 'center' }}
              onClick={() => setType(t.id)}>
              <Icon name={t.i} style={{ fontSize: 18, color: type === t.id ? 'var(--brand-primary)' : 'var(--fg-3)' }} />
              <span style={{ fontSize: 12, fontWeight: 500 }}>{t.l}</span>
            </button>
          ))}
        </div>
      </div>
    </Modal>
  );
}

/* =========================================================
   REPORTS
   ========================================================= */
function ReportsPage({ toast }) {
  const [tab, setTab] = useState('daily');
  const [dailyDate, setDailyDate] = useState(todayISO());
  const [from, setFrom] = useState(daysAgoISO(7));
  const [to, setTo] = useState(todayISO());
  const [downloading, setDownloading] = useState(false);

  const downloadDaily = async () => {
    setDownloading(true);
    try {
      await window.API.downloadDaily(dailyDate);
      toast({ kind: 'success', title: 'Yuklab olindi' });
    } catch (err) {
      toast({ kind: 'danger', title: 'Xato', msg: err.message });
    } finally { setDownloading(false); }
  };
  const downloadPeriod = async () => {
    setDownloading(true);
    try {
      await window.API.downloadPeriod(from, to);
      toast({ kind: 'success', title: 'Yuklab olindi' });
    } catch (err) {
      toast({ kind: 'danger', title: 'Xato', msg: err.message });
    } finally { setDownloading(false); }
  };

  return (
    <div className="page-in">
      <PageHeader title="Hisobotlar" sub="Excel formatda yuklab olish" />

      <Tabs items={[
        { id: 'daily',   label: 'Kunlik',  icon: 'calendar' },
        { id: 'period',  label: 'Davriy',  icon: 'chart-line' },
      ]} value={tab} onChange={setTab} />

      {tab === 'daily' && (
        <Card style={{ padding: 20, marginTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="t-h5">Kunlik kassa hisobot</div>
          <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: 0 }}>
            Bir kunlik barcha vizitlar, xizmatlar, to'lovlar va qarz jadval bilan Excel'ga yuklanadi.
          </p>
          <Field label="Sana">
            <Input type="date" value={dailyDate} onChange={e => setDailyDate(e.target.value)} style={{ width: 200 }} />
          </Field>
          <div>
            <Button variant="primary" icon="export" loading={downloading} onClick={downloadDaily}>
              Excel yuklab olish
            </Button>
          </div>
        </Card>
      )}

      {tab === 'period' && (
        <Card style={{ padding: 20, marginTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="t-h5">Davriy hisobot</div>
          <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: 0 }}>
            Tanlangan davr uchun: umumiy ro'yxat, xizmat bo'yicha, shifokor bo'yicha, to'lov turi bo'yicha alohida sahifalar.
          </p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Field label="Boshlanish"><Input type="date" value={from} onChange={e => setFrom(e.target.value)} style={{ width: 180 }} /></Field>
            <Field label="Tugash"><Input type="date" value={to} onChange={e => setTo(e.target.value)} style={{ width: 180 }} /></Field>
          </div>
          <div>
            <Button variant="primary" icon="export" loading={downloading} onClick={downloadPeriod}>
              Excel yuklab olish
            </Button>
          </div>
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { KassaPage, DebtsPage, PaymentModal, ReportsPage });
