import { Chip, Stack, styled } from '@mui/material'
import { ReactNode, useEffect, useState } from 'react'

type IChip = {
  label: string
  value: string
}

interface ChipsProps {
  list: { label: string | ReactNode; value: string | number }[]
  selected: string[] | string | number
  onSelected: (selected: IChip[] | any) => void
  direction?: 'row' | 'column'
  singleSelection?: boolean
  toggle?: boolean
}

export default function Chips({
  list = [],
  selected: _selected,
  onSelected,
  direction = 'row',
  singleSelection = true,
  toggle = false,
}: ChipsProps) {
  const [selected, setSelected] = useState<any[] | any>([])

  useEffect(() => {
    setSelected(_selected)
  }, [_selected])

  const handleChange = (value) => {
    if (singleSelection) {
      if (selected === value && !toggle) {
        setSelected('')
        onSelected('')
      } else {
        setSelected(value)
        onSelected(value)
      }
    } else {
      if (selected.includes(value)) {
        setSelected((prev) => prev.filter((item) => item !== value))
        onSelected(selected.filter((item) => item !== value))
      } else {
        setSelected([...selected, value])
        onSelected([...selected, value])
      }
    }
  }

  const isSelected = (value) =>
    singleSelection ? selected === value : selected.includes(value)

  return (
    <Stack gap={'8px'} direction={direction} flexWrap={'wrap'}>
      {list.map((item, index) => (
        <StyledChip
          key={index}
          color={'primary'}
          label={item.label}
          clickable
          variant={isSelected(item?.value) ? 'outlined' : 'filled'}
          onClick={() => handleChange(item?.value)}
        />
      ))}
    </Stack>
  )
}

const StyledChip = styled(Chip)(({ theme }) => ({
  minWidth: '100px',
  '&.MuiButtonBase-root.MuiChip-filled': {
    background: theme.palette.secondary.light,
    color: theme.palette.text.primary,
  },
  height: '40px',
  fontSize: '14px',
  fontWeight: 500,
  borderRadius: '20px',
}))
