import { Alert, Badge, Container, Spinner, Table } from 'react-bootstrap';
import { useIngestionStats } from '../api/hooks';
import AppBreadcrumb from '../components/AppBreadcrumb';

function relativeTime(iso: string | null): string {
  if (!iso) return '--';
  const diff = Date.now() - new Date(iso).getTime();
  const seconds = Math.floor(diff / 1000);
  if (seconds < 60) return `${seconds}s ago`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}

function statusBadge(iso: string | null) {
  if (!iso) return <Badge bg="dark">Offline</Badge>;
  const diff = Date.now() - new Date(iso).getTime();
  const minutes = diff / 60_000;
  if (minutes < 5) return <Badge bg="success">Live</Badge>;
  if (minutes < 60) return <Badge bg="warning" text="dark">Stale</Badge>;
  return <Badge bg="dark">Offline</Badge>;
}

export default function MetricsPage() {
  const { data, isLoading, isError, error } = useIngestionStats();

  return (
    <Container>
      <AppBreadcrumb />
      <h5 className="mb-3">Ingestion Metrics</h5>

      {isLoading && <Spinner animation="border" />}
      {isError && <Alert variant="danger">{(error as Error).message}</Alert>}

      {data && (
        <Table striped bordered hover size="sm">
          <thead>
            <tr>
              <th>Exchange</th>
              <th>Pair</th>
              <th>Trades (total)</th>
              <th>Trades (1h)</th>
              <th>Latest Trade</th>
              <th>L1 (total)</th>
              <th>L1 (1h)</th>
              <th>Latest L1</th>
              <th>Est. Storage</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.map((row) => {
              const latestTime = row.latest_trade_time ?? row.latest_l1_time;
              return (
                <tr key={row.instrument_id}>
                  <td>{row.exchange_name}</td>
                  <td>
                    {row.base_asset}-{row.quote_asset}
                  </td>
                  <td>{row.trade_count_total.toLocaleString()}</td>
                  <td>{row.trade_count_1h.toLocaleString()}</td>
                  <td>{relativeTime(row.latest_trade_time)}</td>
                  <td>{row.l1_count_total.toLocaleString()}</td>
                  <td>{row.l1_count_1h.toLocaleString()}</td>
                  <td>{relativeTime(row.latest_l1_time)}</td>
                  <td>{formatBytes(row.estimated_storage_bytes)}</td>
                  <td>{statusBadge(latestTime)}</td>
                </tr>
              );
            })}
          </tbody>
        </Table>
      )}
    </Container>
  );
}
