// @ts-nocheck
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import Button from '../../../../components/Button';
import LoadingSpinner from '../../../../components/LoadingSpinner';
import { useAddFilterMutation, useUpdateFilterMutation } from '../../../../features/filters/filtersApi';

const FooterActions = () => {
  const navigate = useNavigate();
  const filters = useSelector((state) => state.filters);
  const [addFilter, { data, isLoading, isSuccess }] = useAddFilterMutation();
  const [updateFilter, { isLoading: isUpdating, isSuccess: isUpdated }] = useUpdateFilterMutation();

  const handleSave = async () => {
    if (filters?.name.trim() === '') {
      toast.error('Filter name is required');
      return;
    }

    if (filters?.conditions.length < 1) {
      toast.error('Please add some conditions');
      return;
    }

    await addFilter(filters).unwrap();
  };

  const handleUpdate = async () => {
    if (filters?.name.trim() === '') {
      toast.error('Filter name is required');
      return;
    }

    if (filters?.conditions.length < 1) {
      toast.error('Please add some conditions');
      return;
    }
    await updateFilter({ id: filters.id, body: filters }).unwrap();
  };

  useEffect(() => {
    if (isSuccess) {
      toast.success('Filter created successfully');
      navigate(`?id=${data.id}`, { state: { filter: data } });
    }
  }, [isSuccess]);

  useEffect(() => {
    if (isUpdated) {
      toast.success('Filter updated successfully');
    }
  }, [isUpdated]);

  return (
    <div
      style={{ boxShadow: '0px -6px 10px 1px rgba(0,0,0,0.08)' }}
      className='wmx-fixed wmx-z-10 wmx-flex wmx-justify-end wmx-items-center wmx-gap-4 wmx-pe-10 wmx-bottom-0 wmx-left-[179px] wmx-right-0 wmx-border wmx-p-2.5 wmx-bg-white'
    >
      <Button
        type='secondary'
        onClick={() => {
          navigate('/filters');
        }}
      >
        Cancel
      </Button>
      {filters?.id ? (
        <Button onClick={handleUpdate}>
          {isUpdating ? (
            <span className='wmx-flex wmx-items-center wmx-gap-2'>
              Updating... <LoadingSpinner />
            </span>
          ) : (
            'Update Filter'
          )}
        </Button>
      ) : (
        <Button onClick={handleSave} className='disabled:wmx-cursor-not-allowed disabled:wmx-opacity-60'>
          {isLoading ? (
            <span className='wmx-flex wmx-items-center wmx-gap-2 '>
              Saving... <LoadingSpinner />
            </span>
          ) : (
            'Save Filter'
          )}
        </Button>
      )}
    </div>
  );
};
export default FooterActions;
