import { useRef, useState } from 'react';
import Select from 'react-select';
import { useInfiniteQuery } from 'react-query';
import { Spinner } from '@chakra-ui/react';
import { debounce } from 'lodash';

const InfiniteSelect = ({ eventName, name, value, onChange, defaultData }) => {
  const [searchValue, setSearchValue] = useState('');
  const { data, error, fetchNextPage, isFetching, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: [eventName, searchValue], // Include searchValue in the query key
    queryFn: ({ pageParam = 1 }) => {
      return window.grpcAPIs[eventName]({
        search: searchValue, // Use the searchValue
        page: pageParam,
        pageSize: 5,
        orderBy: '',
      });
    },
    getNextPageParam: (lastPage) => {
      return lastPage.page + 1;
    },
    placeholderData: {
      pages: [],
    },
    suspense: true,
  });
  const handleOnSelect = (eventObj) => {
    onChange({ target: { name, value: eventObj.value } });
  };
  const options = data.pages
    ? data.pages.flatMap((page) =>
        page.data.map((option) => ({
          value: option.id,
          label: option.title || option.name || `${option.firstName} ${option.lastName}`,
        })),
      )
    : [];
  if (defaultData) {
    console.log(defaultData.id);
    var defaultDataValue = {
      value: `${defaultData.id}`, // The value of the selected option
      label: defaultData.title ? opdefaultDatation.title : `${defaultData.firstName} ${defaultData.lastName}`, // The label of the selected option
    };
  }
  // Add the spinner as an option when there are more pages to load
  if (isFetchingNextPage || isFetching) {
    options.push({
      value: 'loading',
      label: <Spinner size="sm" />,
    });
  }

  const loadMoreOptions = () => {
    if (hasNextPage && !isFetchingNextPage && !isFetching) {
      fetchNextPage();
    }
  };

  const customStyles = {
    option: (provided) => ({
      ...provided,
      color: 'black',
    }),
  };

  // Function to handle input changes with a delay
  const handleInputChange = (newValue) => {
    setSearchValue(newValue);
  };

  return (
    <div>
      <Select
        options={options}
        isSearchable
        isClearable
        onChange={handleOnSelect}
        onInputChange={handleInputChange} // Use the delayed input change handler
        onMenuScrollToBottom={loadMoreOptions}
        styles={customStyles}
        name={name}
        defaultValue={defaultDataValue}
        // Add other necessary props here
      />
    </div>
  );
};

export default InfiniteSelect;
