import { StatCard, Card, DataTable, Badge, Button, ProgressBar, Spinner } from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useDatabaseStatus, useConnectionPool, useDatabaseTables, useActiveQueries, useKillQuery } from '../../api/queries/admin/database';

export default function DatabaseAdminPage() {
  const { data: status, isError: statusError } = useDatabaseStatus();
  const unreachable = statusError || (status && !status.connected);
  const { data: pool } = useConnectionPool();
  const { data: tables } = useDatabaseTables();
  const { data: queries } = useActiveQueries();
  const killQuery = useKillQuery();

  const poolPct = pool ? (pool.activeConnections / pool.maximumPoolSize) * 100 : 0;

  const tableColumns: Column<any>[] = [
    { key: 'tableName', header: 'Table' },
    { key: 'rowCount', header: 'Rows', sortable: true },
    { key: 'dataSize', header: 'Data Size' },
    { key: 'indexSize', header: 'Index Size' },
  ];

  const queryColumns: Column<any>[] = [
    { key: 'pid', header: 'PID' },
    { key: 'durationSeconds', header: 'Duration', render: (v) => `${v}s` },
    { key: 'state', header: 'State', render: (v) => <Badge label={String(v)} /> },
    { key: 'query', header: 'Query', render: (v) => <span style={{ fontSize: '0.75rem', fontFamily: 'var(--font-mono)' }}>{String(v).slice(0, 80)}</span> },
    {
      key: 'pid', header: '', width: '80px',
      render: (v) => <Button variant="danger" size="sm" onClick={() => killQuery.mutate(v as number)}>Kill</Button>,
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: '1rem' }}>Database Administration</h2>

      <div style={{ display: 'flex', gap: '1rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
        <StatCard label="Status" value={unreachable ? 'Disconnected' : status ? 'Connected' : '\u2014'} accent={unreachable ? 'error' : status ? 'success' : undefined} />
        <StatCard label="Version" value={status?.version ?? '—'} />
      </div>

      {pool && (
        <Card>
          <div style={{ padding: '1rem' }}>
            <h3 style={{ marginBottom: '0.5rem' }}>Connection Pool</h3>
            <ProgressBar value={poolPct} />
            <div style={{ display: 'flex', gap: '2rem', marginTop: '0.5rem', fontSize: '0.875rem' }}>
              <span>Active: {pool.activeConnections}</span>
              <span>Idle: {pool.idleConnections}</span>
              <span>Max: {pool.maximumPoolSize}</span>
            </div>
          </div>
        </Card>
      )}

      <div style={{ marginTop: '1.5rem' }}>
        <h3 style={{ marginBottom: '0.75rem' }}>Tables</h3>
        <DataTable columns={tableColumns} data={(tables || []).map((t: any) => ({ ...t, id: t.tableName }))} sortable pageSize={20} />
      </div>

      <div style={{ marginTop: '1.5rem' }}>
        <h3 style={{ marginBottom: '0.75rem' }}>Active Queries</h3>
        <DataTable columns={queryColumns} data={(queries || []).map((q: any) => ({ ...q, id: String(q.pid) }))} />
      </div>
    </div>
  );
}
