import React from "react";
import { useMutation } from "@tanstack/react-query";
import { Text } from "@mantine/core";
import { modals } from "@mantine/modals";
import getCommonQueryClient from "@/hooks/cruds/baseCrud/getCommonQueryClient";
import {
    CreateDealProductSchema,
    DealProductSchema,
    UpdateDealProductSchema,
} from "@/lib/client";
import {
    createDealProductMutation,
    deleteDealProductMutation,
    getDealProductsQueryKey,
    updateDealProductMutation,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    dealId: number;
};

export type DealProductsCrud = {
    onCreate: (data: CreateDealProductSchema) => void;
    onUpdate: (
        dealId: number,
        serviceId: number,
        data: UpdateDealProductSchema
    ) => void;
    onDelete: (data: DealProductSchema, onSuccess?: () => void) => void;
};

const useDealProductCrud = ({ dealId }: Props): DealProductsCrud => {
    const queryKey = getDealProductsQueryKey({ path: { dealId } });
    const key = "getDealProducts";
    const { queryClient, onError, onSettled } = getCommonQueryClient({
        queryKey,
        key,
    });

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

    const updateMutation = useMutation({
        ...updateDealProductMutation(),
        onError,
        onSettled,
        onMutate: async ({
            body: { entity: update },
            path: { dealId, productId },
        }) => {
            await queryClient.cancelQueries({ queryKey: [key] });

            const previous = queryClient.getQueryData(queryKey);

            queryClient.setQueryData(
                queryKey,
                (old: { items: DealProductSchema[] }) => {
                    const updated: DealProductSchema[] = old.items.map(
                        (entity: DealProductSchema) =>
                            entity.dealId === dealId &&
                            entity.productId === productId
                                ? { ...entity, ...update }
                                : entity
                    );

                    return {
                        ...old,
                        items: updated,
                    };
                }
            );

            return { previous };
        },
    });

    const deleteMutation = useMutation({
        ...deleteDealProductMutation(),
        onError,
        onSettled,
        onMutate: async ({ path: { dealId, productId } }) => {
            await queryClient.cancelQueries({ queryKey: [key] });

            const previous = queryClient.getQueryData(queryKey);

            queryClient.setQueryData(
                queryKey,
                (old: { items: DealProductSchema[] }) => {
                    const filtered = old.items.filter(
                        e => e.dealId !== dealId && e.productId !== productId
                    );
                    return {
                        ...old,
                        items: filtered,
                    };
                }
            );

            return { previous };
        },
    });

    const onCreate = (entity: CreateDealProductSchema) => {
        createMutation.mutate({
            body: {
                entity,
            },
        });
    };

    const onUpdate = (
        dealId: number,
        productId: number,
        entity: UpdateDealProductSchema
    ) => {
        updateMutation.mutate({
            body: {
                entity,
            },
            path: {
                dealId,
                productId,
            },
        });
    };

    const onDelete = (entity: DealProductSchema, onSuccess?: () => void) => {
        modals.openConfirmModal({
            title: "Удаление товара из сделки",
            children: (
                <Text>
                    Вы уверены, что хотите удалить "{entity.product.name}" из
                    сделки?
                </Text>
            ),
            confirmProps: { color: "red" },
            onConfirm: () => {
                deleteMutation.mutate({ path: entity }, { onSuccess });
            },
        });
    };

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

export default useDealProductCrud;
