import React, { useState } from 'react'
import PropTypes from 'prop-types'
import DemioInput from '../DemioInput/DemioInput'
import LinkButton from '../LinkButton/LinkButton'
import './DemioTags.less'

function Tags({
  tags,
  maxLength,
  maxTags,
  placeholder,
  handleInputChange,
  handleInputBlur,
  handleInputFocus,
  handleAddTag,
  handleDeleteTag,
}) {
  const [tagsInput, handleInputStateChange] = useState('')

  const handleTagsInputChange = (value) => {
    if (maxLength && value.length > maxLength) return

    handleInputStateChange(value)

    if (handleInputChange) {
      handleInputChange(value)
    }
  }

  const saveTag = ({ key, target: { value } }) => {
    if (key === 'Enter') {
      handleAddTag(value)
      handleInputStateChange('')
    }
  }

  return (
    <div>
      {tags.length > 0 && (
        <div className="demio-tags-container">
          {tags.map(({ name, id }, index) => (
            <span className="demio-tag" key={id || index}>
              {name}
              <LinkButton className="demio-tag-remove" onClick={() => handleDeleteTag(index)}>
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 10 10">
                  <path
                    fill="#5D676B"
                    d="m6.06 5 3.206-3.205.66-.66a.25.25 0 0 0 0-.354L9.22.074a.25.25 0 0 0-.353 0L5 3.94 1.134.073a.25.25 0 0 0-.353 0L.073.78a.25.25 0 0 0 0 .354L3.94 5 .073 8.866a.25.25 0 0 0 0 .354l.707.707a.25.25 0 0 0 .354 0L5 6.06l3.205 3.205.66.66a.25.25 0 0 0 .354 0l.708-.706a.25.25 0 0 0 0-.354L6.06 5Z"
                  />
                </svg>
              </LinkButton>
            </span>
          ))}
        </div>
      )}
      {tags.length < maxTags && (
        <div className="demio-tags-input">
          <DemioInput
            onKeyUp={saveTag}
            onChange={handleTagsInputChange}
            placeholder={placeholder}
            value={tagsInput}
            onBlur={handleInputBlur}
            onFocus={handleInputFocus}
          />
        </div>
      )}
    </div>
  )
}

Tags.propTypes = {
  tags: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string,
      id: PropTypes.string,
    })
  ),
  maxLength: PropTypes.number,
  maxTags: PropTypes.number,
  placeholder: PropTypes.string,
  handleInputChange: PropTypes.func,
  handleAddTag: PropTypes.func.isRequired,
  handleDeleteTag: PropTypes.func.isRequired,
  handleInputBlur: PropTypes.func,
  handleInputFocus: PropTypes.func,
}

Tags.defaultProps = {
  tags: [],
  maxLength: null,
  maxTags: PropTypes.number,
  placeholder: PropTypes.string,
  handleInputChange: () => {},
  handleInputBlur: () => {},
  handleInputFocus: () => {},
}

export default Tags
