/* eslint-disable no-underscore-dangle */
import * as React from 'react';
import { IconTrash } from '@tabler/icons-react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useSearchParams } from 'react-router';
import ActionPopoverIcon from '@shared/components/ActionPopoverIcon';
import { ChecksService } from '@shared/services';
import { errorMsg, successMsg } from '@shared/utils/utils';
import { log } from '@shared/utils/Logger';
import { removeItemFromPaginatedResult } from '@shared/utils/queryCache';

interface Props {
    testUpdateQuery: any,
    closeHandler?: any,
    size?: number,
    buttonSize?: number,
    check: any
    initCheck?: any
}

export function RemoveButton({ testUpdateQuery, check, closeHandler, initCheck, size = 24, buttonSize }: Props) {
    const queryClient = useQueryClient();
    const [searchParams] = useSearchParams();
    const apikey = searchParams.get('apikey') || undefined;

    const mutationRemoveCheck = useMutation(
        {
            mutationFn: (data: { id: string }) => ChecksService.removeCheck({ ...data, apikey }),
            onSuccess: async () => {
                successMsg({ message: 'Check has been successfully removed' });

                const testId = check.test?._id || check.test;
                queryClient.setQueryData(
                    ['preview_checks', testId],
                    (current: any) => removeItemFromPaginatedResult(current, check._id),
                );
                queryClient.removeQueries({ queryKey: ['check_for_modal', check._id], exact: true });
                queryClient.setQueryData(
                    ['sibling_checks', testId],
                    (current: any) => removeItemFromPaginatedResult(current, check._id),
                );
                await queryClient.refetchQueries(
                    { queryKey: ['related_checks_infinity_pages', initCheck?._id || check._id] },
                );
                await testUpdateQuery.refetch();

                if (closeHandler) closeHandler();
            },
            onError: (e: any) => {
                errorMsg({ error: 'Cannot remove the check' });
                log.error(e);
            },
        },
    );

    const handleRemoveCheckClick = () => {
        mutationRemoveCheck.mutate(
            {
                id: check._id,
            } as any,
        );
    };
    return (
        <ActionPopoverIcon
            testAttr="check-remove-icon"
            variant="subtle"
            icon={<IconTrash stroke={1} size={size} style={{ display: 'block', opacity: 0.88, transform: 'translateY(0.5px)' }} />}
            action={handleRemoveCheckClick}
            title="Delete check"
            testAttrName={check?.name}
            loading={mutationRemoveCheck.isPending}
            confirmLabel="Delete"
            size={buttonSize ?? size}
            color="pink"
            buttonColor="red"
        />
    );
}
