import React, { useMemo } from 'react'

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

import {
  EvictedSQL,
  SQLWithPopover
} from '~/pages/cluster/components/SQLWithPopover'
import { formatValue } from '~/pages/cluster/SQLRepository/migration_shared/format-value'

import {
  formatStatementUserLabel,
  getStatementRecordKey,
  isStatementRUMetricAvailable
} from './statementV2'
import type { StatementV2Model } from './types'

export function useStatementColumns(
  stripUserPrefix: boolean,
  ruMetricAvailable: boolean,
  seriesColorMap?: Record<string, string>
) {
  const { colors } = useMantineTheme()

  return useMemo<MRT_ColumnDef<StatementV2Model>[]>(() => {
    const getUserLabel = (row: StatementV2Model) =>
      row.user ? formatStatementUserLabel(row.user, stripUserPrefix) : '-'

    const columns: MRT_ColumnDef<StatementV2Model>[] = [
      {
        id: 'digest_text',
        header: 'Statement Template',
        minSize: 300,
        enableSorting: false,
        accessorFn: (row) => row.digest_text || row.digest || '-',
        Cell: ({ row }) => {
          const color =
            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: color, 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 (isStatementRUMetricAvailable(ruMetricAvailable)) {
      columns.push(
        {
          id: 'sum_ru',
          header: 'Total RU',
          enableResizing: false,
          accessorFn: (row) => getValueFormat('short')(row.sum_ru ?? 0, 2, 2)
        },
        {
          id: 'avg_ru',
          header: 'Mean RU',
          enableResizing: false,
          accessorFn: (row) => getValueFormat('short')(row.avg_ru ?? 0, 2, 2)
        }
      )
    }

    return columns
  }, [colors.carbon, ruMetricAvailable, seriesColorMap, stripUserPrefix])
}
