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

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

import styles from './styles.module.scss';

function FilterSuggester({ options = [], ...props }) {
  const filterValue = options?.find((option) => option.id === props.value);

  const handleSearch = (event) => {
    props.onSearch(event?.target?.value || '');
  };

  const handleChange = (event, value) => {
    props.onChange(props.type, value?.id);
  };

  return (
    <Autocomplete
      value={filterValue}
      size="small"
      onOpen={handleSearch}
      onChange={handleChange}
      onInputChange={handleSearch}
      loading={!options}
      options={options || []}
      className={styles.Suggester}
      optionLabelKey="name"
      optionValueKey="id"
      data-id={`filter-${props.type}`}
      isOptionEqualToValue={(option, value) => option.id === value.id}
      renderInput={(params) => <TextField {...params} variant="outlined" placeholder={props.label} />}
    />
  );
}

FilterSuggester.propTypes = {
  type: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  options: PropTypes.arrayOf(PropTypes.shape({})),
  onSearch: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
  value: PropTypes.string.isRequired,
};

export default FilterSuggester;
