import { StatCard, DataTable } from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useClickHouseStatus, useClickHouseTables, useClickHousePerformance, useClickHouseQueries } from '../../api/queries/admin/clickhouse';
import styles from './ClickHouseAdminPage.module.css';
import tableStyles from '../../styles/table-section.module.css';

export default function ClickHouseAdminPage() {
  const { data: status, isError: statusError } = useClickHouseStatus();
  const { data: tables } = useClickHouseTables();
  const { data: perf } = useClickHousePerformance();
  const { data: queries } = useClickHouseQueries();
  const unreachable = statusError || (status && !status.reachable);

  const totalSize = (tables || []).reduce((sum, t) => sum + (t.dataSizeBytes || 0), 0);
  const totalSizeLabel = totalSize > 0 ? formatBytes(totalSize) : '';

  const tableColumns: Column<any>[] = [
    { key: 'name', header: 'Table', sortable: true },
    { key: 'engine', header: 'Engine' },
    { key: 'rowCount', header: 'Rows', sortable: true, render: (v) => Number(v).toLocaleString() },
    { key: 'dataSize', header: 'Size', sortable: true },
    { key: 'partitionCount', header: 'Partitions', sortable: true },
  ];

  const queryColumns: Column<any>[] = [
    { key: 'elapsedSeconds', header: 'Elapsed', render: (v) => `${v}s` },
    { key: 'memory', header: 'Memory' },
    { key: 'readRows', header: 'Rows Read', render: (v) => Number(v).toLocaleString() },
    { key: 'query', header: 'Query', render: (v) => <span className={styles.queryText}>{String(v).slice(0, 100)}</span> },
  ];

  return (
    <div>
      {/* Status */}
      <div className={styles.statStrip}>
        <StatCard label="Status" value={unreachable ? 'Disconnected' : status ? 'Connected' : '\u2014'} accent={unreachable ? 'error' : status ? 'success' : undefined} />
        <StatCard label="Version" value={status?.version ?? '\u2014'} />
        <StatCard label="Uptime" value={status?.uptime ?? '\u2014'} />
      </div>

      {/* Storage overview */}
      {perf && (
        <div className={styles.statStrip}>
          <StatCard label="Disk Size" value={perf.diskSize} />
          <StatCard label="Uncompressed" value={perf.uncompressedSize} />
          <StatCard label="Compression" value={`${perf.compressionRatio}x`} />
          <StatCard label="Total Rows" value={perf.totalRows.toLocaleString()} />
          <StatCard label="Parts" value={perf.partCount.toLocaleString()} />
          <StatCard label="Memory" value={perf.memoryUsage} />
        </div>
      )}

      {/* Tables */}
      <div className={`${tableStyles.tableSection} ${styles.tableSection}`}>
        <div className={tableStyles.tableHeader}>
          <span className={tableStyles.tableTitle}>Tables ({(tables || []).length})</span>
          {totalSizeLabel && <span className={tableStyles.tableMeta}>{totalSizeLabel} total</span>}
        </div>
        <DataTable
          columns={tableColumns}
          data={(tables || []).map((t: any) => ({ ...t, id: t.name }))}
          sortable
          pageSize={20}
          flush
        />
      </div>

      {/* Active Queries */}
      <div className={`${tableStyles.tableSection} ${styles.tableSection}`}>
        <div className={tableStyles.tableHeader}>
          <span className={tableStyles.tableTitle}>Active Queries ({(queries || []).length})</span>
        </div>
        <DataTable
          columns={queryColumns}
          data={(queries || []).map((q: any, i: number) => ({ ...q, id: q.queryId || String(i) }))}
          flush
        />
      </div>
    </div>
  );
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  const val = bytes / Math.pow(1024, i);
  return `${val.toFixed(val < 10 ? 2 : 1)} ${units[i]}`;
}
