import React from 'react'
import { useMemo } from 'react'

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

import { SQLWithPopover } from './_shared/SQLWithPopover'
import { TOP_SQL_OTHERS_LABEL } from './display'
import { formatSharePercentage } from './formatters'
import { TopSQLTableRecord } from './types'

interface TopSQLTableProps {
  data: TopSQLTableRecord[]
  loading?: boolean
  selectedKey?: string
  highlightedKey?: string
  seriesColorMap: Record<string, string>
  onSelect: (key: string) => void
  onHover: (trendKey: string) => void
  onLeave: () => void
  onRowClick?: (record: TopSQLTableRecord) => void
}

const TopSQLTable: React.FC<React.PropsWithChildren<TopSQLTableProps>> = ({
  data,
  loading,
  selectedKey,
  highlightedKey,
  seriesColorMap,
  onSelect,
  onHover,
  onLeave,
  onRowClick
}) => {
  const { colors } = useMantineTheme()

  const columns = useMemo<MRT_ColumnDef<TopSQLTableRecord>[]>(() => {
    const commonColumns: MRT_ColumnDef<TopSQLTableRecord>[] = [
      {
        id: 'rank',
        header: '#',
        size: 50,
        minSize: 50,
        maxSize: 50,
        enableSorting: false,
        accessorFn: (row) => row.key,
        Cell: ({ row }) => String(row.index + 1).padStart(2, '0')
      },
      {
        id: 'primary',
        header: 'SQL Statement',
        minSize: 320,
        enableSorting: false,
        accessorFn: (row) => row.sql,
        Cell: ({ row }) => {
          const record = row.original
          const sql = record.sql
          const indicatorColor =
            seriesColorMap[record.trendKey] || colors.carbon[4]

          return (
            <Box data-testid='top-sql-sql-cell' sx={{ width: '100%' }}>
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <Box
                  w={4}
                  h={16}
                  mt={4}
                  data-testid='top-sql-sql-series-indicator'
                  data-trend-key={record.trendKey}
                  sx={{ backgroundColor: indicatorColor, flexShrink: 0 }}
                />
                <Box sx={{ flex: 1, minWidth: 0 }}>
                  {record.isOthers ? (
                    <Typography fs='italic' c='carbon.7'>
                      {TOP_SQL_OTHERS_LABEL}
                    </Typography>
                  ) : (
                    <SQLWithPopover sql={sql} />
                  )}
                </Box>
              </Box>
            </Box>
          )
        }
      },
      {
        id: 'totalRU',
        header: 'Total RU',
        size: 120,
        accessorFn: (row) => getValueFormat('short')(row.totalRU, 2, 2)
      },
      {
        id: 'meanRU',
        header: 'Mean RU',
        size: 120,
        accessorFn: (row) => getValueFormat('short')(row.meanRU, 2, 2)
      },
      {
        id: 'share',
        header: 'Share',
        size: 128,
        minSize: 128,
        Cell: ({ row }) => (
          <Box sx={{ width: '100%' }} pr='lg'>
            <Flex align='center' gap='sm' sx={{ width: '100%' }}>
              <Typography
                variant='body-lg'
                sx={{ minWidth: 35, flexShrink: 0 }}
              >
                {formatSharePercentage(row.original.share)}
              </Typography>
              <Progress
                value={row.original.share}
                size={8}
                color='peacock.8'
                sx={{ flex: 1 }}
                styles={{ root: { backgroundColor: '#DCE3E5' } }}
              />
            </Flex>
          </Box>
        )
      },
      {
        id: 'executions',
        header: 'Executions',
        size: 120,
        accessorFn: (row) => getValueFormat('short')(row.executions, 0, 1)
      },
      {
        id: 'totalLatency',
        header: 'Total Latency',
        size: 140,
        accessorFn: (row) => getValueFormat('ns')(row.totalLatencyNs, 1)
      },
      {
        id: 'meanLatency',
        header: 'Mean Latency',
        size: 140,
        accessorFn: (row) => getValueFormat('ns')(row.meanLatencyNs, 1)
      }
    ]

    return commonColumns
  }, [colors.carbon, seriesColorMap])

  return (
    <ProTable<TopSQLTableRecord>
      data-testid='top-sql-table'
      emptyMessage='No Data'
      layoutMode='grid'
      enableSorting={false}
      enableColumnPinning
      columns={columns}
      data={data}
      state={{ isLoading: loading }}
      initialState={{ columnPinning: { left: ['rank', 'primary'] } }}
      mantinePaperProps={{ mx: 0 }}
      mantineTableBodyRowProps={({ row }) => {
        const isSelected = row.original.key === selectedKey
        const isHighlighted = row.original.trendKey === highlightedKey

        return {
          'data-testid': 'top-sql-table-row',
          'data-record-key': row.original.key,
          className: 'wd-cursor-pointer',
          onClick: () => {
            if (loading) {
              return
            }

            onSelect(row.original.key)
            onRowClick?.(row.original)
          },
          onMouseEnter: () => onHover(row.original.trendKey),
          onMouseLeave: onLeave,
          sx: (theme) => ({
            cursor: 'pointer',
            backgroundColor: isSelected
              ? theme.colors.blue[0]
              : isHighlighted
              ? theme.colors.carbon[1]
              : undefined
          })
        }
      }}
    />
  )
}

export default TopSQLTable
