import { Group, Stack, Typography } from '@tidbcloud/uikit'
import { Dot } from '@tidbcloud/uikit/biz'
import { ReactNode } from 'react'

import TimeComponent from 'dbaas/components/TimeComponent'

import { TypeIcon } from './TypeIcon'

export const MessageItem = ({
  title,
  subject,
  type,
  sendAt,
  isActive,
  isRead,
  isFirst,
  handleItemClick
}: {
  title?: string
  subject?: string
  type: string
  sendAt?: string
  isActive: boolean
  isRead: boolean
  isFirst: boolean
  handleItemClick: () => void
}) => {
  let newType = type
  let subjectComp: ReactNode = subject
  // a hack way to implement index advisor notification ux
  if (title?.startsWith('New Index Advisor Tip')) {
    newType = 'index_advisor'

    const subjectObj = JSON.parse(subject ?? '')
    if (subjectObj) {
      subjectComp = (
        <>
          TiDB Bot detected a slow query. Our Index Advisor suggests an improvement that could boost performance by{' '}
          <Typography variant="label-lg" component="span">
            {(subjectObj.improvement * 100).toFixed(2)}%
          </Typography>{' '}
          and save{' '}
          <Typography variant="label-lg" component="span">
            ${subjectObj.cost_saving_monthly}
          </Typography>{' '}
          in monthly costs.
        </>
      )
    }
  }

  return (
    <Group
      tabIndex={0}
      gap="sm"
      py={8}
      px={8}
      mt={isFirst ? 4 : 0}
      mb={4}
      sx={(theme) => ({
        borderRadius: theme.radius.md,
        cursor: 'pointer',
        border: `1px solid ${isActive ? theme.colors.carbon[9] : 'transparent'}`,
        ':hover': {
          border: `1px solid ${isActive ? theme.colors.carbon[9] : theme.colors.carbon[5]}`
        }
      })}
      align="flex-start"
      onClick={handleItemClick}
    >
      <Group gap="sm" mt={4}>
        {isRead ? <Dot color="blue" sx={{ opacity: 0, width: 8 }} /> : <Dot color="blue" bg="peacock.7" size={8} />}
        <TypeIcon type={newType} />
      </Group>
      <Stack gap={4} sx={{ flex: 1, flexWrap: 'wrap' }}>
        <Typography variant="action-md" c="carbon.9">
          {title}
        </Typography>
        <Typography
          variant="body-sm"
          c="carbon.8"
          sx={{
            display: '-webkit-box',
            '-webkit-box-orient': 'vertical',
            '-webkit-line-clamp': '2',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}
        >
          {subjectComp}
        </Typography>
        <Typography variant="body-sm" c="carbon.7">
          <TimeComponent time={sendAt || ''} />
        </Typography>
      </Stack>
    </Group>
  )
}
