import { Box, Stack, Typography } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { useMemo } from 'react'

import TimeComponent from 'dbaas/components/TimeComponent'
import { CloudProvidersDescription } from 'dbaas/features/Billing/provider'
import { Dedicatedv1beta1CustomerManagedEncryptionKey } from 'dbaas/services/api-clients/v2023/dedicated/v1beta1/interface'

import { useCmekList } from './helper'

export const EncryptionList = () => {
  const { data: cmekList, isLoading } = useCmekList()

  const columns = useMemo<MRT_ColumnDef<Dedicatedv1beta1CustomerManagedEncryptionKey>[]>(
    () => [
      {
        id: 'id',
        header: 'Key ID',
        accessorKey: 'customerManagedEncryptionKeyId'
      },
      {
        header: 'Cloud',
        Cell: ({ row: rowData }) => {
          const row = rowData.original
          const providerNameIdx = row.regionId.indexOf('-')
          if (providerNameIdx > -1) {
            return <Box>{CloudProvidersDescription[row.regionId.substring(0, providerNameIdx).toUpperCase()]} </Box>
          }
          return null
        }
      },
      {
        id: 'region',
        header: 'Region',
        accessorKey: 'regionDisplayName'
      },
      {
        id: 'createdTime',
        header: 'Created at',
        accessorFn: (row) => <TimeComponent time={row.createTime || ''}></TimeComponent>
      }
    ],
    []
  )

  return (
    <ProTable
      withBorder
      columns={columns}
      loading={isLoading}
      mantineTableProps={{
        verticalSpacing: 8
      }}
      mantinePaperProps={{ mx: 24 }}
      data={cmekList?.cmeks || []}
      renderEmptyRowsFallback={() => (
        <Box
          sx={{
            height: 'calc(100vh - 280px)',
            backgroundColor: 'var(--mantine-color-carbon-0)'
          }}
        >
          <Stack gap={24} align="center" justify="center" maw={720} h="100%" m="auto">
            <Typography fz={18} fw={700} c="carbon.7" ta="center">
              Customer-Managed Encryption Keys (CMEK)
            </Typography>
            <Typography variant="body-lg" c="carbon.7" ta="center" sx={{ textWrap: 'balance' }}>
              CMEK allow you to protect data at rest in your TiDB Cloud Dedicated cluster.
            </Typography>
          </Stack>
        </Box>
      )}
    />
  )
}
