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

import { Autocomplete, TextField } from '@/mui/components';

function AutocompleteFilter({ disabled = false, label = '', ...props }) {
  return (
    <Autocomplete
      data-id="autocomplete"
      id={`${props.id}-autocomplete`}
      value={props.value[0] ?? null}
      size={props.size}
      options={props.options}
      onOpen={() => props.onOpen('')}
      onChange={(e, value) => {
        props.onChange(value ? [value] : []);

        if (value?.value) {
          props.onGetContentOwners(value.value);
        }
      }}
      groupBy={props.groupBy}
      loading={props.loading}
      disabled={disabled}
      filterSelectedOptions
      renderInput={(params) => (
        <TextField
          {...params}
          label={label}
          placeholder={props.placeholder}
          onChange={(e) => props.onInputChange(e.target.value)}
          variant="outlined"
          disabled={disabled}
        />
      )}
    />
  );
}

AutocompleteFilter.propTypes = {
  id: PropTypes.string.isRequired,
  value: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string,
    }),
  ).isRequired,
  options: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  loading: PropTypes.bool.isRequired,
  disabled: PropTypes.bool,
  placeholder: PropTypes.string.isRequired,
  label: PropTypes.string,

  onOpen: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
  groupBy: PropTypes.func.isRequired,
  onInputChange: PropTypes.func.isRequired,
  onGetContentOwners: PropTypes.func.isRequired,
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']).isRequired,
};

export default AutocompleteFilter;
