import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';

import { TagIabSelector } from '@/modules/@common/TagSelector';

function ActionIAB({ onChange = null, value = [], size = 'medium', placeholder = null, disabled = false, ...props }) {
  const [list, setList] = useState(value);

  useEffect(() => setList(value), [value]);

  const selectedTags = useMemo(
    () =>
      list.map((tag) => ({
        initialNode: { ...tag },
        label: tag.label,
        value: tag.id,
        include: tag.include,
      })),
    [list],
  );

  return (
    <TagIabSelector
      {...props}
      size={size}
      disabled={disabled}
      value={selectedTags}
      placeholder={placeholder}
      onChange={(event, tags) => {
        const newTags = tags.map((tag) => ({
          ...tag.initialNode,
          include: tag.include,
        }));

        setList(newTags);

        if (onChange) {
          onChange(newTags);
        }
      }}
    />
  );
}

ActionIAB.propTypes = {
  id: PropTypes.string.isRequired,
  onChange: PropTypes.func,
  value: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string,
    }),
  ),
  placeholder: PropTypes.string,
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']),
  disabled: PropTypes.bool,
};

export default ActionIAB;
