import { Box, Tooltip } from '@tidbcloud/uikit'
import { createStyles } from '@tidbcloud/uikit/emotion'
import { IconCheck } from '@tidbcloud/uikit/icons'
import { clsx } from '@tidbcloud/uikit/utils'
import { isNil } from 'lodash-es'
import { observer } from 'mobx-react'
import { useCallback, useEffect, useState } from 'react'

import { ChartIcon, ChartSelectorItem } from '../../type'

interface PropsType {
  value?: string | null
  data: (ChartSelectorItem & { icon?: ChartIcon; disabledMsg?: string })[]
  onChange?: (value: string, data: ChartSelectorItem) => void
}

const useStyles = createStyles((theme) => ({
  option: {
    height: '28px',
    display: 'flex',
    cursor: 'pointer',
    alignItems: 'center',
    padding: '0 12px 0 20px',
    borderRadius: '8px',
    color: theme.colors.carbon[8],
    '&:hover': {
      background: theme.colors.carbon[3],
      color: theme.colors.carbon[8]
    }
  },
  select: {
    background: `${theme.colors.carbon[4]} !important`,
    color: `${theme.colors.carbon[9]} !important`,
    path: {
      stroke: theme.colors.carbon[9]
    }
  },
  label: {
    flex: 1,
    fontWeight: 400,
    fontSize: '12px',
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis'
  },
  disabled: {
    opacity: 0.3
  }
}))

export const ChartSelector: React.FC<React.PropsWithChildren<PropsType>> = observer(({ value, data, onChange }) => {
  const [selected, setSelected] = useState<string | null>(null)
  const { classes } = useStyles()

  useEffect(() => {
    value !== undefined && setSelected(value)
  }, [value])

  const handleClick = useCallback((newValue: string, dataItem: ChartSelectorItem) => {
    if (dataItem.disabled) return
    setSelected(newValue)
    onChange?.(newValue, dataItem)
  }, [])

  return (
    <>
      {data.map((dataItem) => {
        const item = (
          <Box
            key={dataItem.label}
            className={clsx(
              classes.option,
              dataItem.value === selected ? classes.select : '',
              dataItem.disabled ? classes.disabled : ''
            )}
            onClick={() => handleClick(dataItem.value, dataItem)}
          >
            {dataItem.icon && <Box component={dataItem.icon as any} mr={10} size={16} />}
            <div className={classes.label}>{dataItem.label}</div>
            {dataItem.value === selected && <Box component={IconCheck} mr={10} size={16} />}
          </Box>
        )
        return dataItem.disabled && !isNil(dataItem.disabledMsg) ? (
          <Tooltip label={dataItem.disabledMsg} withArrow openDelay={300}>
            {item}
          </Tooltip>
        ) : (
          <Tooltip label={dataItem.label} openDelay={300}>
            {item}
          </Tooltip>
        )
      })}
    </>
  )
})
