// This file is part of Coog. The COPYRIGHT file at the top level of
// this repository contains the full copyright notices and license terms.

import React, { FC, useState } from 'react';
import ReactSelect from 'react-select';

import { SelectProps } from './Select.types';
import { Field } from '../Select/Select.types';
import { getInitialValue, getOptions } from './Select.service';
import { getSelectedValue } from '../utils';
import { styleCustom } from './Select.utils';

import './Select.scss';

/**
 * @description Select - made for Formik
 * @param {function} eventEmitter
 * @param {FormikField} field
 * @param {boolean} isMulti - optionnal / default false
 * @returns Select component
 */
const Select: FC<SelectProps> = ({
  eventEmitter,
  field,
  isMulti = false,
  options,
  placeholder = null,
  disabled,
  width,
  height,
  minWidthMenu,
}: SelectProps): JSX.Element => {
  const [localValue, setLocalValue] = useState(getInitialValue(field, isMulti, options));
  const [localOptions, setLocalOptions] = useState(getOptions(options));

  const changeHandler = (selectedOption: Field, actionMeta: Record<string, string>) => {
    const value = getSelectedValue({ value: selectedOption, isMulti });
    setLocalValue(selectedOption);
    eventEmitter(value, actionMeta);
  };

  return (
    <div data-testid="Select" className="select-45a88392-bbf6-49c0-8b24-262e4b183da1">
      <ReactSelect
        className="coog-select"
        options={localOptions}
        value={localValue}
        placeholder={placeholder}
        onChange={changeHandler}
        isMulti={isMulti}
        isDisabled={disabled}
        styles={styleCustom({ width, height, minWidthMenu })}
      />
    </div>
  );
};

export default Select;
