import React from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Text } from "@mantine/core";
import { modals } from "@mantine/modals";
import { HttpValidationError, UpdateDealGroupSchema } from "@/lib/client";
import {
    createDealGroupMutation,
    deleteDealGroupMutation,
    updateDealGroupMutation,
    updateDealsInGroupMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

export type GroupsCrud = {
    onUpdate: (groupId: number, group: UpdateDealGroupSchema) => void;
    onCreate: (mainDealId: number, otherDealIds: number[]) => void;
    onUpdateDealsInGroup: (groupId: number, dealIds: number[]) => void;
    onDelete: (groupId: number) => void;
};

const useDealGroupCrud = (): GroupsCrud => {
    const queryClient = useQueryClient();
    const key = "getDeals";

    const onError = (
        error: AxiosError<HttpValidationError>,
        _: any,
        context: any
    ) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
        if (context?.previous) {
            queryClient.setQueryData([key], context.previous);
        }
    };

    const onSettled = () => {
        queryClient.invalidateQueries({
            predicate: (query: { queryKey: any }) =>
                query.queryKey[0]?._id === key,
        });
    };

    const updateMutation = useMutation({
        ...updateDealGroupMutation(),
        onSettled,
        onError,
    });

    const onUpdate = (groupId: number, entity: UpdateDealGroupSchema) => {
        updateMutation.mutate({
            path: {
                pk: groupId,
            },
            body: {
                entity,
            },
        });
    };

    const createMutation = useMutation({
        ...createDealGroupMutation(),
        onSettled,
        onError,
    });

    const onCreate = (mainDealId: number, otherDealIds: number[]) => {
        createMutation.mutate({
            body: {
                mainDealId,
                otherDealIds,
            },
        });
    };

    const updateDealsMutation = useMutation({
        ...updateDealsInGroupMutation(),
        onSettled,
        onError,
    });

    const onUpdateDealsInGroup = (groupId: number, dealIds: number[]) => {
        updateDealsMutation.mutate({
            path: {
                pk: groupId,
            },
            body: {
                dealIds,
            },
        });
    };

    const deleteMutation = useMutation({
        ...deleteDealGroupMutation(),
        onSettled,
        onError,
    });

    const onDelete = (groupId: number) => {
        modals.openConfirmModal({
            title: "Удаление группы",
            children: <Text>Вы уверены, что хотите удалить группу?</Text>,
            confirmProps: { color: "red" },
            onConfirm: () => {
                deleteMutation.mutate({
                    path: {
                        pk: groupId,
                    },
                });
            },
        });
    };

    return {
        onUpdate,
        onCreate,
        onUpdateDealsInGroup,
        onDelete,
    };
};

export default useDealGroupCrud;
