import React, { useEffect, useState } from 'react';
import Select from 'react-select';
import { connect } from 'react-redux';

const customStyles = {
  control: provided => ({
    ...provided,
    background: '#f1f1f6',
    border: 'none',
    minHeight: '44px',
  }),
  multiValue: provided => ({
    ...provided,
    backgroundColor: '#ffffff',
  }),
};

const MultiSelectComponent = ({
  formData,
  updateLogicProperty,
  elementDetails,
  index,
  value,
}) => {
  const [selectOptions, setSelectOptions] = useState([]);

  useEffect(() => {
    const availableOptions = [];
    const allPages = [];
    const usedAsTargets = [];
    formData.map(page => {
      allPages.push([...page.elements]);
    });
    const flatPage = allPages.flat();
    flatPage.map(item => {
      if (item?.logics?.length > 0) {
        item.logics.map(target => {
          if (item.unique_id !== elementDetails.unique_id) {
            target.targets.map(used => {
              usedAsTargets.push(used.value);
            });
          }
        });
      }
    });

    flatPage.map(item => {
      if (
        !usedAsTargets.includes(item.unique_id) &&
        item.unique_id !== elementDetails.unique_id
      ) {
        availableOptions.push({ label: item.label, value: item.unique_id });
      }
    });
    setSelectOptions(availableOptions);
  }, [formData]);

  return (
    <div>
      <Select
        onChange={val => updateLogicProperty(index, val, 'targets')}
        options={selectOptions}
        isMulti={true}
        value={value}
        styles={customStyles}
        isSearchable
      />
    </div>
  );
};

const mapStateToProps = state => ({
  formData: state.formBuilder.formData,
});

export default connect(mapStateToProps, null)(MultiSelectComponent);
