import { useState } from 'react';
import { Card, KpiStrip, Spinner } from '@cameleer/design-system';
import { Database, ChevronDown, ChevronRight } from 'lucide-react';
import {
  useInfraPostgres,
  useInfraClickHouse,
  useInfraPgDetail,
  useInfraChDetail,
} from '../../api/vendor-hooks';
import type { TenantPgStats, TenantChStats } from '../../api/vendor-hooks';

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

function formatUptime(seconds: number): string {
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

function formatNumber(n: number): string {
  return n.toLocaleString();
}

const thStyle: React.CSSProperties = {
  textAlign: 'left',
  padding: '8px 16px',
  fontSize: 11,
  fontWeight: 600,
  color: 'var(--text-muted)',
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
  borderBottom: '1px solid var(--border)',
};

const tdStyle: React.CSSProperties = {
  padding: '10px 16px',
  fontSize: 13,
  borderBottom: '1px solid var(--border)',
  fontVariantNumeric: 'tabular-nums',
};

const monoStyle: React.CSSProperties = {
  fontFamily: 'var(--font-mono, monospace)',
  fontSize: 12,
};

// --- PG Detail Row ---

function PgDetailRow({ slug }: { slug: string }) {
  const { data, isLoading } = useInfraPgDetail(slug);

  if (isLoading) {
    return (
      <tr>
        <td colSpan={5} style={{ ...tdStyle, textAlign: 'center' }}>
          <Spinner size="sm" />
        </td>
      </tr>
    );
  }
  if (!data || data.length === 0) {
    return (
      <tr>
        <td colSpan={5} style={{ ...tdStyle, color: 'var(--text-muted)', textAlign: 'center' }}>
          No tables found
        </td>
      </tr>
    );
  }

  return (
    <tr>
      <td colSpan={5} style={{ padding: 0 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', background: 'var(--surface-2)' }}>
          <thead>
            <tr>
              <th style={{ ...thStyle, paddingLeft: 48 }}>Table</th>
              <th style={{ ...thStyle, textAlign: 'right' }}>Rows</th>
              <th style={{ ...thStyle, textAlign: 'right' }}>Data Size</th>
              <th style={{ ...thStyle, textAlign: 'right' }}>Index Size</th>
            </tr>
          </thead>
          <tbody>
            {data.map((t) => (
              <tr key={t.tableName}>
                <td style={{ ...tdStyle, ...monoStyle, paddingLeft: 48 }}>{t.tableName}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{formatNumber(t.rowCount)}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{formatBytes(t.dataSizeBytes)}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{formatBytes(t.indexSizeBytes)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </td>
    </tr>
  );
}

// --- CH Detail Row ---

function ChDetailRow({ tenantId }: { tenantId: string }) {
  const { data, isLoading } = useInfraChDetail(tenantId);

  if (isLoading) {
    return (
      <tr>
        <td colSpan={3} style={{ ...tdStyle, textAlign: 'center' }}>
          <Spinner size="sm" />
        </td>
      </tr>
    );
  }
  if (!data || data.length === 0) {
    return (
      <tr>
        <td colSpan={3} style={{ ...tdStyle, color: 'var(--text-muted)', textAlign: 'center' }}>
          No tables found
        </td>
      </tr>
    );
  }

  return (
    <tr>
      <td colSpan={3} style={{ padding: 0 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', background: 'var(--surface-2)' }}>
          <thead>
            <tr>
              <th style={{ ...thStyle, paddingLeft: 48 }}>Table</th>
              <th style={{ ...thStyle, textAlign: 'right' }}>Rows</th>
            </tr>
          </thead>
          <tbody>
            {data.map((t) => (
              <tr key={t.tableName}>
                <td style={{ ...tdStyle, ...monoStyle, paddingLeft: 48 }}>{t.tableName}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{formatNumber(t.rowCount)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </td>
    </tr>
  );
}

// --- PostgreSQL Tenant Row ---

function PgTenantRow({ tenant }: { tenant: TenantPgStats }) {
  const [expanded, setExpanded] = useState(false);
  const chevron = expanded
    ? <ChevronDown size={14} style={{ color: 'var(--text-muted)' }} />
    : <ChevronRight size={14} style={{ color: 'var(--text-muted)' }} />;

  return (
    <>
      <tr
        style={{ cursor: 'pointer' }}
        onClick={() => setExpanded((e) => !e)}
      >
        <td style={{ ...tdStyle, ...monoStyle, display: 'flex', alignItems: 'center', gap: 8 }}>
          {chevron} {tenant.slug}
        </td>
        <td style={{ ...tdStyle, textAlign: 'right' }}>{formatBytes(tenant.schemaSizeBytes)}</td>
        <td style={{ ...tdStyle, textAlign: 'right' }}>{formatNumber(tenant.tableCount)}</td>
        <td style={{ ...tdStyle, textAlign: 'right' }}>{formatNumber(tenant.totalRows)}</td>
      </tr>
      {expanded && <PgDetailRow slug={tenant.slug} />}
    </>
  );
}

// --- ClickHouse Tenant Row ---

function ChTenantRow({ tenant }: { tenant: TenantChStats }) {
  const [expanded, setExpanded] = useState(false);
  const tablePreview = Object.entries(tenant.rowsByTable)
    .slice(0, 3)
    .map(([tbl, rows]) => `${tbl}: ${formatNumber(rows)}`)
    .join(', ');
  const chevron = expanded
    ? <ChevronDown size={14} style={{ color: 'var(--text-muted)' }} />
    : <ChevronRight size={14} style={{ color: 'var(--text-muted)' }} />;

  return (
    <>
      <tr
        style={{ cursor: 'pointer' }}
        onClick={() => setExpanded((e) => !e)}
      >
        <td style={{ ...tdStyle, ...monoStyle, display: 'flex', alignItems: 'center', gap: 8 }}>
          {chevron} {tenant.tenantId}
        </td>
        <td style={{ ...tdStyle, textAlign: 'right' }}>{formatNumber(tenant.totalRows)}</td>
        <td style={{ ...tdStyle, color: 'var(--text-muted)', fontSize: 12 }}>
          {tablePreview || '\u2014'}
          {Object.keys(tenant.rowsByTable).length > 3 ? ' \u2026' : ''}
        </td>
      </tr>
      {expanded && <ChDetailRow tenantId={tenant.tenantId} />}
    </>
  );
}

// --- Section Header ---

function SectionHeader({ title, loading, error }: { title: string; loading?: boolean; error?: boolean }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
      <Database size={18} style={{ color: 'var(--amber)' }} />
      <h2 style={{ margin: 0, fontSize: '1rem', fontWeight: 600 }}>{title}</h2>
      {loading && <Spinner size="sm" />}
      {error && <span style={{ fontSize: 13, color: 'var(--error, #ef4444)' }}>Failed to load</span>}
    </div>
  );
}

// --- Main Page ---

export function InfrastructurePage() {
  const pg = useInfraPostgres();
  const ch = useInfraClickHouse();

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 960 }}>
      <h1 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 600 }}>Infrastructure</h1>

      {/* PostgreSQL Card */}
      <Card>
        <SectionHeader title="PostgreSQL" loading={pg.isLoading} error={pg.isError} />

        {pg.data && (
          <>
            <div style={{ padding: '4px 20px' }}>
              <KpiStrip
                items={[
                  { label: 'Version', value: pg.data.overview.version.split(' ').slice(0, 2).join(' ') },
                  { label: 'Database Size', value: formatBytes(pg.data.overview.databaseSizeBytes) },
                  { label: 'Active Connections', value: String(pg.data.overview.activeConnections) },
                ]}
              />
            </div>

            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={thStyle}>Tenant</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>Schema Size</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>Tables</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>Rows</th>
                </tr>
              </thead>
              <tbody>
                {pg.data.tenants.length === 0 ? (
                  <tr>
                    <td colSpan={4} style={{ ...tdStyle, color: 'var(--text-muted)', textAlign: 'center' }}>
                      No tenant schemas found
                    </td>
                  </tr>
                ) : (
                  pg.data.tenants.map((t) => (
                    <PgTenantRow key={t.slug} tenant={t} />
                  ))
                )}
              </tbody>
            </table>
          </>
        )}
      </Card>

      {/* ClickHouse Card */}
      <Card>
        <SectionHeader title="ClickHouse" loading={ch.isLoading} error={ch.isError} />

        {ch.data && (
          <>
            <div style={{ padding: '4px 20px' }}>
              <KpiStrip
                items={[
                  { label: 'Version', value: ch.data.overview.version },
                  { label: 'Uptime', value: formatUptime(ch.data.overview.uptimeSeconds) },
                  { label: 'Disk Usage', value: formatBytes(ch.data.overview.totalDiskBytes) },
                  { label: 'Total Rows', value: formatNumber(ch.data.overview.totalRows) },
                  { label: 'Compression', value: `${ch.data.overview.compressionRatio.toFixed(1)}x` },
                  { label: 'Active Merges', value: String(ch.data.overview.activeMerges) },
                ]}
              />
            </div>

            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={thStyle}>Tenant</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>Total Rows</th>
                  <th style={thStyle}>By Table</th>
                </tr>
              </thead>
              <tbody>
                {ch.data.tenants.length === 0 ? (
                  <tr>
                    <td colSpan={3} style={{ ...tdStyle, color: 'var(--text-muted)', textAlign: 'center' }}>
                      No tenant data found
                    </td>
                  </tr>
                ) : (
                  ch.data.tenants.map((t) => (
                    <ChTenantRow key={t.tenantId} tenant={t} />
                  ))
                )}
              </tbody>
            </table>
          </>
        )}
      </Card>
    </div>
  );
}
