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

const useDealProductActions = () => {
    const { dealProductsList, dealProductsCrud, deal } =
        useFulfillmentBaseContext();

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

        const productIdsToExclude = dealProductsList.dealProducts.map(
            product => product.product.id
        );

        modals.openContextModal({
            modal: "dealProductEditorModal",
            title: "Добавление товара",
            withCloseButton: false,
            innerProps: {
                onCreate: values =>
                    dealProductsCrud.onCreate({ ...values, dealId: deal.id }),
                productIdsToExclude,
                isEditing: false,
                clientId: deal.client.id,
            },
        });
    };

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

        modals.openContextModal({
            modal: "dealProductEditorModal",
            title: "Добавление товара",
            withCloseButton: false,
            innerProps: {
                onChange: values =>
                    dealProductsCrud.onUpdate(
                        dealProduct.dealId,
                        dealProduct.productId,
                        values
                    ),
                entity: dealProduct,
                isEditing: true,
                clientId: deal.client.id,
            },
        });
    };

    return {
        onCreateClick,
        onChangeClick,
    };
};

export default useDealProductActions;
