import React, { useState } from 'react'
import { Space, Tag, Input, Button } from 'antd'
import PlusIcon from '../../Icons/PlusIcon'
import PropTypes from 'prop-types'

const TagsInput = ({ value = [], onChange }) => {
  const [inputValue, setInputValue] = useState('')

  const handleTagClose = (removedTag) => {
    const newTags = value.filter((tag) => tag !== removedTag)
    onChange && onChange(newTags)
  }

  const handleTagAdd = () => {
    const newTag = inputValue.trim()
    if (newTag && !value.includes(newTag)) {
      const newTags = [...value, newTag]
      onChange && onChange(newTags)
      setInputValue('')
    }
  }

  return (
    <>
      <Space size={'small'} wrap style={{ marginBottom: 4, maxWidth: '300px' }}>
        {value.map((tag) => (
          <Tag
            key={tag}
            color='blue'
            closable
            onClose={() => handleTagClose(tag)}
            style={{ marginBottom: 12, marginRight: 0 }}
          >
            {tag}
          </Tag>
        ))}
      </Space>
      <Space.Compact block>
        <Input
          placeholder='Add new tag'
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onPressEnter={handleTagAdd}
        />
        <Button onClick={handleTagAdd} icon={<PlusIcon />} />
      </Space.Compact>
    </>
  )
}

TagsInput.propTypes = {
  value: PropTypes.arrayOf(PropTypes.string),
  onChange: PropTypes.func
}

export default TagsInput
