import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import LoadingSpinner from '../../../components/LoadingSpinner';
import { useGetDropdownQuery } from '../../../features/dropdown/dropdownApi';
import { useGetFilterQuery } from '../../../features/filters/filtersApi';
import { setCompleteFilterState } from '../../../features/filters/filtersSlice';
import ConditionsCard from './components/ConditionsCard/ConditionsCard';
import FilterName from './components/FilterName';
import FooterActions from './components/FooterActions';

const FilterEditor = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [searchParams] = useSearchParams();
  const filterId = searchParams.get('id');
  const { state } = useLocation();
  const [loading, setLoading] = useState(true);
  const [skip, setSkip] = useState(true);
  const { data, isLoading, isError } = useGetFilterQuery(filterId, { skip });
  const { data: allFilters, isLoading: isFiltersLoading } = useGetDropdownQuery('filters');

  useEffect(() => {
    if (state && filterId) {
      dispatch(setCompleteFilterState(state.filter));
      setLoading(false);
    } else {
      if (filterId) {
        setSkip(false);
      } else {
        setLoading(false);
      }
    }
  }, [state, filterId]);

  useEffect(() => {
    if (data) {
      dispatch(setCompleteFilterState(data));
      setLoading(false);
      setSkip(true);
    }
  }, [data]);

  useEffect(() => {
    if (isError) {
      navigate('/filters');
    }
  }, [isError]);

  if (loading || isLoading) {
    return (
      <div className='wmx-h-[420px] wmx-flex wmx-justify-center wmx-items-center'>
        <LoadingSpinner className='wmx-size-10' />
      </div>
    );
  }

  return (
    <div className='wmx-flex wmx-gap-4'>
      <div className='wmx-flex-grow wmx-pb-4'>
        <FilterName />
        <ConditionsCard allFilters={allFilters} isLoading={isFiltersLoading} />
        <FooterActions />
      </div>
    </div>
  );
};
export default FilterEditor;
