import React from 'react';

import { PublisherType } from '../../types';

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

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

type FilterSuggesterProps = {
  type: string;
  label: string;
  options: PublisherType[];
  value: string | null;
  onSearch: (value: string) => void;
  onChange: (type: string, id: string) => void;
};

function FilterSuggester({ options = [], type, label, value, onSearch, onChange }: FilterSuggesterProps) {
  const filterValue = options.find((option) => option.id === value);

  const handleSearch = (event: React.SyntheticEvent<Element, Event>) => {
    const target = event?.target as HTMLInputElement;
    onSearch(target?.value || filterValue?.name || '');
  };

  const handleChange = (event: React.SyntheticEvent<Element, Event>, option: unknown) => {
    const option$ = option as PublisherType;
    onChange(type, option$?.id);
    onSearch(option$?.name || '');
  };

  return (
    <Autocomplete
      value={filterValue?.name ?? null}
      clearOnBlur
      blurOnSelect
      clearOnEscape
      options={options}
      onChange={handleChange}
      onOpen={handleSearch}
      onInputChange={handleSearch}
      loading={!options.length}
      optionLabelKey="name"
      optionValueKey="name"
      size="small"
      data-id={`filter-${type}`}
      className={styles.Suggester}
      renderInput={(params) => <TextField {...params} placeholder={label} />}
    />
  );
}

export default FilterSuggester;
