import { useState } from 'react';
import { StatCard, Card, DataTable, Badge, Button, ProgressBar, Spinner, AlertDialog, useToast } from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useDatabaseStatus, useConnectionPool, useDatabaseTables, useActiveQueries, useKillQuery } from '../../api/queries/admin/database';
import styles from './DatabaseAdminPage.module.css';
import tableStyles from '../../styles/table-section.module.css';

export default function DatabaseAdminPage() {
  const { toast } = useToast();
  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 [killTarget, setKillTarget] = useState<number | null>(null);

  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 className={styles.querySnippet}>{String(v).slice(0, 80)}</span> },
    {
      key: 'pid', header: '', width: '80px',
      render: (v) => <Button variant="danger" size="sm" onClick={() => setKillTarget(v as number)}>Kill</Button>,
    },
  ];

  return (
    <div>
      <div className={styles.pageTitle}>Database Administration</div>

      <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 ?? '—'} />
      </div>

      {pool && (
        <Card>
          <div className={styles.cardBody}>
            <div className={styles.sectionTitle}>Connection Pool</div>
            <ProgressBar value={poolPct} />
            <div className={styles.poolStats}>
              <span>Active: {pool.activeConnections}</span>
              <span>Idle: {pool.idleConnections}</span>
              <span>Max: {pool.maximumPoolSize}</span>
            </div>
          </div>
        </Card>
      )}

      <div className={tableStyles.tableSection}>
        <div className={tableStyles.tableHeader}>
          <span className={tableStyles.tableTitle}>Tables</span>
        </div>
        <DataTable columns={tableColumns} data={(tables || []).map((t: any) => ({ ...t, id: t.tableName }))} sortable pageSize={20} />
      </div>

      <div className={tableStyles.tableSection}>
        <div className={tableStyles.tableHeader}>
          <span className={tableStyles.tableTitle}>Active Queries</span>
        </div>
        <DataTable columns={queryColumns} data={(queries || []).map((q: any) => ({ ...q, id: String(q.pid) }))} />
      </div>

      <AlertDialog
        open={killTarget !== null}
        onClose={() => setKillTarget(null)}
        onConfirm={() => {
          if (killTarget !== null) {
            killQuery.mutate(killTarget, {
              onSuccess: () => {
                toast({ title: 'Query killed', description: `PID ${killTarget}`, variant: 'success' });
                setKillTarget(null);
              },
              onError: () => {
                toast({ title: 'Failed to kill query', variant: 'error', duration: 86_400_000 });
                setKillTarget(null);
              },
            });
          }
        }}
        title="Kill query?"
        description={`Terminate the query running on PID ${killTarget}? This will cancel the operation.`}
        confirmLabel="Kill"
        variant="warning"
      />
    </div>
  );
}
