import { DocumentDuplicateIcon, PencilSquareIcon, TrashIcon } from '@heroicons/react/24/outline';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import LoadingSpinner from '../../../../components/LoadingSpinner';
import { useAddFilterMutation } from '../../../../features/filters/filtersApi';

const FilterActions = ({ filter, setDeleteId, setShowDeleteModal }) => {
  const [addFilter, { isLoading }] = useAddFilterMutation();
  const handleDuplicateFilter = async (data) => {
    try {
      const duplicateData = { ...data };
      delete duplicateData.created_date;
      delete duplicateData.updated_date;
      duplicateData.name = data.name + ' (Copy)';
      await addFilter(duplicateData).unwrap();
      toast.success('Filter duplicated successfully');
    } catch {
      toast.error('Failed to duplicate badge');
    }
  };

  const navigate = useNavigate();
  return (
    <span className='wmx-flex wmx-items-center wmx-justify-center wmx-gap-2'>
      <button
        onClick={() => {
          navigate(`editor?id=${filter.id}`, { state: { filter } });
        }}
      >
        <PencilSquareIcon className='wmx-w-5 wmx-h-5' />
      </button>

      {!isLoading ? (
        <button
          onClick={() => {
            handleDuplicateFilter(filter);
          }}
        >
          <DocumentDuplicateIcon className='wmx-w-5 wmx-h-5' />
        </button>
      ) : (
        <LoadingSpinner size={5} />
      )}

      <button
        onClick={() => {
          setDeleteId(filter.id);
          setShowDeleteModal(true);
        }}
      >
        <TrashIcon className='wmx-w-5 wmx-h-5' />
      </button>
    </span>
  );
};
export default FilterActions;
