import { useEffect, useState } from 'react';
import { fetchAdminLedger, fetchAdminUsage, type LedgerEntry, type UsageRecord } from '../../api/admin';

type Tab = 'ledger' | 'usage';

function yuan(cents: number) {
  return `¥${(cents / 100).toFixed(2)}`;
}

function fmtTime(ts: string) {
  return new Date(ts).toLocaleString('zh-CN', { hour12: false });
}

export function BillingPage() {
  const [tab, setTab] = useState<Tab>('ledger');

  return (
    <div className="grid">
      <div className="card" style={{ display: 'flex', gap: 8 }}>
        <button
          type="button"
          className={tab === 'ledger' ? 'btn' : 'btn secondary'}
          onClick={() => setTab('ledger')}
        >
          余额账本
        </button>
        <button
          type="button"
          className={tab === 'usage' ? 'btn' : 'btn secondary'}
          onClick={() => setTab('usage')}
        >
          用量记录
        </button>
      </div>
      {tab === 'ledger' ? <LedgerTab /> : <UsageTab />}
    </div>
  );
}

function LedgerTab() {
  const [entries, setEntries] = useState<LedgerEntry[]>([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const load = async (p: number) => {
    setLoading(true);
    setError(null);
    try {
      const result = await fetchAdminLedger({ page: p, pageSize: 30 });
      setEntries(result.entries);
      setTotal(result.total);
      setTotalPages(result.totalPages);
      setPage(p);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { void load(1); }, []);

  return (
    <>
      {error ? <p className="alert">{error}</p> : null}
      <div className="card" style={{ overflowX: 'auto', padding: 0 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f5f0e5', borderBottom: '1px solid #d6d0c3' }}>
              {['时间', '用户', '类型', '金额', '备注'].map((h) => (
                <th key={h} style={{ padding: '10px 12px', textAlign: 'left', fontWeight: 600 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {entries.map((e) => (
              <tr key={e.id} style={{ borderBottom: '1px solid #ebe4d6' }}>
                <td style={{ padding: '10px 12px', whiteSpace: 'nowrap', color: '#68716c' }}>{fmtTime(e.createdAt)}</td>
                <td style={{ padding: '10px 12px' }}><code style={{ fontSize: 11 }}>{e.username ?? e.userId}</code></td>
                <td style={{ padding: '10px 12px' }}>{e.type}</td>
                <td
                  style={{
                    padding: '10px 12px',
                    color: e.amountCents >= 0 ? '#2f6f57' : '#b42318',
                    fontVariantNumeric: 'tabular-nums',
                  }}
                >
                  {e.amountCents >= 0 ? '+' : ''}{yuan(e.amountCents)}
                </td>
                <td style={{ padding: '10px 12px', color: '#68716c', maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.note || '—'}</td>
              </tr>
            ))}
            {entries.length === 0 && !loading ? (
              <tr><td colSpan={5} style={{ padding: 24, textAlign: 'center', color: '#68716c' }}>暂无记录</td></tr>
            ) : null}
          </tbody>
        </table>
      </div>
      <Pagination page={page} totalPages={totalPages} total={total} unit="条" onGo={load} />
    </>
  );
}

function UsageTab() {
  const [records, setRecords] = useState<UsageRecord[]>([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const load = async (p: number) => {
    setLoading(true);
    setError(null);
    try {
      const result = await fetchAdminUsage({ page: p, pageSize: 30 });
      setRecords(result.records);
      setTotal(result.total);
      setTotalPages(result.totalPages);
      setPage(p);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { void load(1); }, []);

  return (
    <>
      {error ? <p className="alert">{error}</p> : null}
      <div className="card" style={{ overflowX: 'auto', padding: 0 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f5f0e5', borderBottom: '1px solid #d6d0c3' }}>
              {['时间', '用户', 'Provider', '模型', '输入', '输出', '费用'].map((h) => (
                <th key={h} style={{ padding: '10px 12px', textAlign: 'left', fontWeight: 600 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {records.map((r) => (
              <tr key={r.id} style={{ borderBottom: '1px solid #ebe4d6' }}>
                <td style={{ padding: '10px 12px', whiteSpace: 'nowrap', color: '#68716c' }}>{fmtTime(r.createdAt)}</td>
                <td style={{ padding: '10px 12px' }}><code style={{ fontSize: 11 }}>{r.username ?? r.userId}</code></td>
                <td style={{ padding: '10px 12px' }}>{r.provider}</td>
                <td style={{ padding: '10px 12px', maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.model}</td>
                <td style={{ padding: '10px 12px', fontVariantNumeric: 'tabular-nums' }}>{r.inputTokens.toLocaleString()}</td>
                <td style={{ padding: '10px 12px', fontVariantNumeric: 'tabular-nums' }}>{r.outputTokens.toLocaleString()}</td>
                <td style={{ padding: '10px 12px', color: '#b54708', fontVariantNumeric: 'tabular-nums' }}>{yuan(r.costCents)}</td>
              </tr>
            ))}
            {records.length === 0 && !loading ? (
              <tr><td colSpan={7} style={{ padding: 24, textAlign: 'center', color: '#68716c' }}>暂无记录</td></tr>
            ) : null}
          </tbody>
        </table>
      </div>
      <Pagination page={page} totalPages={totalPages} total={total} unit="条" onGo={load} />
    </>
  );
}

function Pagination({
  page, totalPages, total, unit, onGo,
}: {
  page: number; totalPages: number; total: number; unit: string; onGo: (p: number) => void;
}) {
  if (totalPages <= 1) return null;
  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
      <button type="button" className="btn secondary" disabled={page <= 1} onClick={() => onGo(page - 1)}>上一页</button>
      <span style={{ fontSize: 13, color: '#68716c' }}>第 {page} / {totalPages} 页（共 {total} {unit}）</span>
      <button type="button" className="btn secondary" disabled={page >= totalPages} onClick={() => onGo(page + 1)}>下一页</button>
    </div>
  );
}
