import { modals } from "@mantine/modals";
import { notifications } from "@/lib/notifications";
import { useFulfillmentBaseContext } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";
import { DealProductSchema } from "@/lib/client";

const useProductActions = () => {
    const { deal, dealProductsList, productsCrud } =
        useFulfillmentBaseContext();

    const onCreateClick = () => {
        if (!deal.client) {
            notifications.error({ message: "Выберите клиента для сделки" });
            return;
        }

        modals.openContextModal({
            modal: "productEditorModal",
            title: "Создание товара",
            withCloseButton: false,
            innerProps: {
                onCreate: productsCrud.onCreate,
                isEditing: false,
                clientId: deal.client.id,
                refetchProducts: dealProductsList.refetch,
            },
        });
    };

    const onChangeClick = (dealProduct: DealProductSchema) => {
        modals.openContextModal({
            modal: "productEditorModal",
            title: "Редактирование товара",
            withCloseButton: false,
            innerProps: {
                onChange: values =>
                    productsCrud.onUpdate(
                        dealProduct.productId,
                        values,
                        dealProductsList.refetch
                    ),
                entity: dealProduct.product,
                isEditing: true,
                clientId: dealProduct.product.clientId,
                refetchProducts: dealProductsList.refetch,
            },
        });
    };

    return {
        onCreateClick,
        onChangeClick,
    };
};

export default useProductActions;
