import React, { useState } from "react"
import Select from "react-select"
import { MultiSelectProps } from "./interfaces"
import * as S from "./styles"
import Option from "./components/Option"
import MultiValue from "./components/MultiValue"

const MultiSelectInput:React.FC<MultiSelectProps> = ({
  className,
  label,
  onChange,
  placeholder,
  disabled,
  options,
  value,
  isSearchable,
  isClearable,
}) => {
  const [valueSelected, setValueSelected] = useState(value)

  const components = {
    MultiValueContainer: ({ selectProps, data }: any) => {
      const values = selectProps.value;
      if (values) {
        const separator = values.length > 1 ? ', ' : ''
        return values[values.length - 1]?.label === data?.label
          ? data?.label
          : data?.label + `${separator}`;
      }
      return
    },
    Option, 
    MultiValue
  };

  return (
    <S.Container className={className}>
      { label ? <S.Label>{label}</S.Label> : null }
      <Select
        placeholder={placeholder}
        className="react-select-container"
        classNamePrefix="react-select"
        defaultValue={valueSelected || []}
        options={options}
        isMulti
        closeMenuOnSelect={false}
        hideSelectedOptions={false}
        isDisabled={disabled}
        isSearchable={isSearchable}
        isClearable={isClearable}
        components={components}
        onChange={(values: any) => {
          setValueSelected(values) 
          onChange(values)
        }}
      />
    </S.Container>
  )
}

export default MultiSelectInput 