import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import LoadingSpinner from '../../../../../components/LoadingSpinner';
import SingleSelect from '../../../../../components/SingleSelect';
import { changeBadgeBaseProperties } from '../../../../../features/badges/badgesSlice';
import { useGetFiltersQuery } from '../../../../../features/filters/filtersApi';

const SelectFilter = () => {
  const dispatch = useDispatch();
  const [filters, setFilters] = useState({});
  const { filter } = useSelector((state) => state.badges);
  const { data, isLoading, isFetching, isError } = useGetFiltersQuery();

  const handleFilterChange = (value) => {
    dispatch(changeBadgeBaseProperties({ name: 'filter', value: Number(value) }));
  };

  useEffect(() => {
    if (!isLoading && data) {
      setFilters(Object.fromEntries(data.map((item) => [item.id, item.name])));
    }
  }, [data]);

  if (isLoading || isFetching) {
    return <LoadingSpinner />;
  }

  if (isError) {
    return <p className='wmx-text-base'>No Filter Found, Please Create Some Filters First.</p>;
  }

  return (
    <SingleSelect
      placeholder={'Select Filter'}
      inputClass='wmx-w-80'
      onChange={handleFilterChange}
      selected={String(filter)}
      items={filters}
    />
  );
};
export default SelectFilter;
