import React from 'react';
import PropTypes from 'prop-types';

import { MenuItem, Select } from '@/mui/components';

function FilterSelector({ size = 'medium', ...props }) {
  const onChange = ({ target }) => {
    const prop = props.config?.options.find((item) => item.value === target.value);

    props.selectAction({
      ...props.config,
      value: [prop],
    });
  };

  return (
    <Select
      size={size}
      data-id={`select-${props.config?.dataId}-options`}
      value={props.selected[0]?.value ?? props.config?.defaultValue}
      onChange={onChange}
    >
      {props.config?.options.map(({ label, value }) => (
        <MenuItem key={value} value={value}>
          {label}
        </MenuItem>
      ))}
    </Select>
  );
}

FilterSelector.propTypes = {
  config: PropTypes.shape({
    options: PropTypes.arrayOf(
      PropTypes.shape({
        value: PropTypes.string,
      }),
    ),
    dataId: PropTypes.string,
    defaultValue: PropTypes.string,
  }).isRequired,
  selected: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string,
    }),
  ).isRequired,
  selectAction: PropTypes.func.isRequired,
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']),
};

export default FilterSelector;
