import { getValueFormat } from '@baurine/grafana-value-formats'
import { Box, Typography, useMantineTheme } from '@tidbcloud/uikit'
import { MRT_ColumnDef } from '@tidbcloud/uikit/biz'
import { useMemo } from 'react'

import { ComputedClusterProps } from 'dbaas/features/ClusterManagement/cluster'
import { EvictedSQL, SQLWithPopover } from 'dbaas/screens/ClusterV2/features/Diagnosis/components/SQLWithPopover'
import { StatementModel } from 'dbaas/screens/ClusterV2/features/Diagnosis/Statement/utils/type'
import { formatValue } from 'dbaas/screens/ClusterV2/features/Diagnosis/utils/formatValue'

import { formatStatementUserLabel, getStatementRecordKey } from './statementV2'

export const useStatementColumns = (computed: ComputedClusterProps, seriesColorMap?: Record<string, string>) => {
  const { colors } = useMantineTheme()

  const columns = useMemo<MRT_ColumnDef<StatementModel>[]>(() => {
    const getUserLabel = (row: StatementModel) => {
      const user = row.user
      return user ? formatStatementUserLabel(user, computed.isEssential) : '-'
    }

    const cols: MRT_ColumnDef<StatementModel>[] = [
      {
        id: 'digest_text',
        header: 'Statement Template',
        minSize: 300,
        enableSorting: false,
        accessorFn: (row) => row.digest_text || row.digest || '-',
        Cell: ({ row }) => {
          const sqlColor =
            seriesColorMap?.[row.original.digest || ''] ||
            seriesColorMap?.[getStatementRecordKey(row.original)] ||
            colors.carbon[4]

          return (
            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 12, width: '100%' }}>
              <Box w={4} h={16} mt={4} sx={{ backgroundColor: sqlColor, flexShrink: 0 }} />
              <Box sx={{ flex: 1, minWidth: 0 }}>
                {row.original.digest_text ? (
                  <SQLWithPopover sql={row.original.digest_text} />
                ) : row.original.digest ? (
                  <Typography variant="body-lg">{row.original.digest}</Typography>
                ) : (
                  <EvictedSQL />
                )}
              </Box>
            </Box>
          )
        }
      },
      {
        id: 'user',
        header: 'DB User',
        size: 140,
        accessorFn: getUserLabel,
        Cell: ({ row }) => (
          <Typography variant="body-lg" truncate>
            {getUserLabel(row.original)}
          </Typography>
        )
      },
      {
        id: 'schema_name',
        header: 'DB',
        size: 140,
        accessorFn: (row) => row.schema_name || '-',
        Cell: ({ row }) => (
          <Typography variant="body-lg" truncate>
            {row.original.schema_name || '-'}
          </Typography>
        )
      },
      {
        id: 'table_names',
        header: 'Tables',
        size: 180,
        accessorFn: (row) => row.table_names || '-',
        Cell: ({ row }) => (
          <Typography variant="body-lg" truncate>
            {row.original.table_names || '-'}
          </Typography>
        )
      },
      {
        id: 'digest',
        header: 'SQL Digest',
        size: 220,
        accessorFn: (row) => row.digest || '-',
        Cell: ({ row }) => (
          <Typography variant="body-lg" truncate>
            {row.original.digest || '-'}
          </Typography>
        )
      },
      {
        id: 'sum_latency',
        header: 'Total Latency',
        enableResizing: false,
        accessorFn: (row) => formatValue(row, 'sum_latency', 'ns')
      },
      {
        id: 'avg_latency',
        header: 'Mean Latency',
        enableResizing: false,
        accessorFn: (row) => formatValue(row, 'avg_latency', 'ns')
      },
      {
        id: 'exec_count',
        header: 'Executions Count',
        enableResizing: false,
        accessorFn: (row) => formatValue(row, 'exec_count', 'short')
      },
      {
        id: 'plan_count',
        header: 'Plans Count',
        enableResizing: false,
        accessorFn: (row) => row.plan_count ?? 0
      }
    ]

    if (computed.isServerless || computed.isPremium || computed.isEssentialV2) {
      cols.push({
        id: 'sum_ru',
        header: 'Total RU',
        enableResizing: false,
        accessorFn: (row) => getValueFormat('short')(row.sum_ru ?? 0, 2, 2)
      })
      cols.push({
        id: 'avg_ru',
        header: 'Mean RU',
        enableResizing: false,
        accessorFn: (row) => getValueFormat('short')(row.avg_ru ?? 0, 2, 2)
      })
    }

    return cols
  }, [
    colors.carbon,
    computed.isEssential,
    computed.isEssentialV2,
    computed.isPremium,
    computed.isServerless,
    seriesColorMap
  ])

  return columns
}
