import React, { CSSProperties } from 'react'

import { Box, Table } from '@tidbcloud/uikit'
import { createStyles } from '@tidbcloud/uikit/emotion'

const useStyles = createStyles((theme) => ({
  tr: {
    '&:hover': {
      backgroundColor: theme.colors.carbon[3]
    }
  }
}))

export interface Column {
  key: string
  name: string
  element?: React.FC<
    React.PropsWithChildren<{
      value: any
      data: any[]
      rowIndex: number
      columnIndex: number
    }>
  >
  tdStyle?: CSSProperties
}

const InfoTable = <T,>({
  columns,
  data = []
}: {
  columns: Column[]
  data?: T[]
}) => {
  const { classes } = useStyles()

  return (
    <Box
      sx={(theme) => ({
        border: `1px solid ${theme.colors.carbon[4]}`,
        borderRadius: theme.defaultRadius,
        overflow: 'hidden'
      })}
    >
      <Table verticalSpacing='md' horizontalSpacing='xl'>
        <Table.Thead>
          <Table.Tr sx={(theme) => ({ background: theme.colors.carbon[2] })}>
            {columns.map((c) => (
              <Table.Th key={c.key}>{c.name}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>

        <Table.Tbody>
          {data.map((d, index) => (
            <Table.Tr key={index} className={classes.tr}>
              {columns.map((c, columnIndex) => {
                return (
                  <Table.Td key={c.key} style={c.tdStyle}>
                    {/* @ts-ignore */}
                    {c.element
                      ? c.element({
                          value: d[c.key as keyof T],
                          data,
                          rowIndex: index,
                          columnIndex
                        })
                      : d[c.key as keyof T]}
                  </Table.Td>
                )
              })}
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
    </Box>
  )
}

export default InfoTable
