import { getValueFormat } from '@baurine/grafana-value-formats'
import { Typography, Tooltip } from '@tidbcloud/uikit'
import React, { useMemo } from 'react'

import { useTimeFormatter } from 'dbaas/components/TimeComponent'

import InfoTable from '../../components/InfoTable'
import { isNextGenCluster } from '../../utils/formatValue'
import { useStatementContext } from '../utils/context'
import { StatementModel } from '../utils/type'

type ColumnType = {
  name: string
  value: React.ReactNode
  description?: string
}

export const PlanDetailTabBasic: React.FC<React.PropsWithChildren<{ data: StatementModel }>> = ({ data }) => {
  const ctx = useStatementContext()
  const timeFormatter = useTimeFormatter()
  const isNextGen = isNextGenCluster(ctx.cfg.computed)

  const tableData = useMemo<ColumnType[]>(() => {
    const cols = [
      {
        name: 'Table Names',
        value: data.table_names || '-',
        description: ''
      },
      {
        name: 'Index Names',
        value: data.index_names || '-',
        description: 'The name of the used index'
      },
      {
        name: 'First Seen',
        value: data.first_seen ? timeFormatter(data.first_seen) : '-',
        description: ''
      },
      {
        name: 'Last Seen',
        value: data.last_seen ? timeFormatter(data.last_seen) : '-',
        description: ''
      },
      {
        name: 'Executions Count',
        value: getValueFormat('short')(data.exec_count ?? 0, 0, 1),
        description: 'Total execution count for this kind of statement'
      },
      {
        name: 'Total Latency',
        value: getValueFormat('ns')(data.sum_latency ?? 0, 1),
        description: 'Total execution time for this kind of statement'
      },
      {
        name: 'Execution User',
        value: data.sample_user || '-',
        description: 'The user that executes the query (sampled)'
      },
      {
        name: 'Total Errors',
        value: getValueFormat('short')(data.sum_errors ?? 0, 0, 1)
      },
      {
        name: 'Total Warnings',
        value: getValueFormat('short')(data.sum_warnings ?? 0, 0, 1)
      }
    ]
    if (!isNextGen) {
      cols.push(
        ...[
          {
            name: 'Mean Memory',
            value: getValueFormat('bytes')(data.avg_mem ?? 0, 1),
            description: 'Memory usage of single query'
          },
          {
            name: 'Max Memory',
            value: getValueFormat('bytes')(data.max_mem ?? 0, 1),
            description: 'Maximum memory usage of single query'
          },
          {
            name: 'Mean Disk',
            value: getValueFormat('bytes')(data.avg_disk ?? 0, 1),
            description: 'Disk usage of single query'
          },
          {
            name: 'Max Disk',
            value: getValueFormat('bytes')(data.max_disk ?? 0, 1),
            description: 'Maximum disk usage of single query'
          }
        ]
      )
    }
    if (ctx.cfg.computed.isServerless || ctx.cfg.computed.isPremium || ctx.cfg.computed.isEssentialV2) {
      cols.push({
        name: 'Total RU',
        value: getValueFormat('short')(data.sum_ru ?? 0, 2, 2)
      })
      cols.push({
        name: 'Mean RU',
        value: getValueFormat('short')(data.avg_ru ?? 0, 2, 2)
      })
    }
    return cols
  }, [data, ctx.cfg.computed])

  return (
    <InfoTable<ColumnType>
      columns={[
        {
          key: 'name',
          name: 'Name',
          element: ({ value }) => <Typography className="wd-truncate">{value}</Typography>
        },
        {
          key: 'value',
          name: 'Value',
          element: ({ value }) => (
            <Tooltip label={value} position="top-start" withArrow>
              <Typography className="wd-truncate">{value}</Typography>
            </Tooltip>
          ),
          tdStyle: { maxWidth: '300px' }
        },
        {
          key: 'description',
          name: 'Description',
          tdStyle: { maxWidth: '400px' },
          element: ({ value }) => (
            <Tooltip label={value} position="top-start" withArrow maw={300} multiline>
              <Typography className="wd-truncate">{value}</Typography>
            </Tooltip>
          )
        }
      ]}
      data={tableData}
    />
  )
}
