import { Box } from '@tidbcloud/uikit'
import { createStyles } from '@tidbcloud/uikit/emotion'
import { clsx } from '@tidbcloud/uikit/utils'
import { observer } from 'mobx-react'
import { useCallback, useEffect, useState } from 'react'

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

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

const useStyles = createStyles((theme) => ({
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    width: '100%',
    padding: '0 20px'
  },
  option: {
    flex: 1,
    height: '24px',
    display: 'flex',
    cursor: 'pointer',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '0 20px',
    margin: '2px',
    borderRadius: '3px',
    color: theme.colors.carbon[8],
    background: theme.colors.carbon[2],
    '&:hover': { background: theme.colors.carbon[3] }
  },
  selected: {
    background: `${theme.colors.carbon[9]} !important`,
    color: `${theme.colors.carbon[0]} !important`
  },
  disabled: {
    opacity: 0.3
  }
}))

export const AggregationSelector: 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 (
      <div className={classes.root}>
        {data.map((dataItem) => (
          <Box
            key={dataItem.label}
            className={clsx(
              classes.option,
              dataItem.value === selected ? classes.selected : '',
              dataItem.disabled ? classes.disabled : ''
            )}
            onClick={() => handleClick(dataItem.value, dataItem)}
          >
            {dataItem.label}
          </Box>
        ))}
      </div>
    )
  }
)
