import React, {useCallback, useState} from 'react'
import useClassNames from '../../shared/useClassNames'
import Icon from '../icon/index'

import './index.less'

type TagProps = {
  name: string
  closable?: boolean
  color?: string
  background?: string
  prefixCls?: string
  className?: string
  afterClose?(name: string): void
  onClick?(name: string): void
}

const Tag: React.FC<TagProps> = ({
  name,
  closable,
  color,
  background,
  prefixCls,
  className,
  onClick,
  afterClose,
}: TagProps) => {
  const [visible, setVisible] = useState(true)
  const newClassName = useClassNames('tag', prefixCls, {}, className)
  const closeDom = () => <Icon className="close-icon" name="close" onClick={() => onClose()} />
  const tagBgStyle = color ? {borderColor: color, color, background} : {}
  const onClose = useCallback(() => {
    setVisible(false)
    afterClose?.(name)
  }, [visible])
  if (!visible) return <div />
  return (
    <div className={newClassName} onClick={() => onClick?.(name)} style={tagBgStyle}>
      {name}
      {closable && closeDom()}
    </div>
  )
}

export default Tag
