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

type Props = {
    dealProduct: DealProductSchema;
};

const useProductServicesTable = ({ dealProduct }: Props) => {
    const { productServiceCrud, dealProductsList } =
        useFulfillmentBaseContext();

    const onChange = (item: ProductServiceSchema) => {
        const excludeServiceIds = dealProduct.productServices.map(
            productService => productService.service.id
        );
        const totalQuantity = dealProductsList.dealProducts.reduce(
            (sum, prod) => prod.quantity + sum,
            0
        );

        modals.openContextModal({
            modal: "productServiceEditorModal",
            innerProps: {
                entity: item,
                onChange: values =>
                    productServiceCrud.onUpdate(
                        item.dealId,
                        item.productId,
                        item.serviceId,
                        values
                    ),
                excludeServiceIds,
                quantity: totalQuantity,
                isEditing: true,
            },
            withCloseButton: false,
        });
    };

    const onCreate = () => {
        const excludeServiceIds = dealProduct.productServices.map(
            productService => productService.service.id
        );

        modals.openContextModal({
            modal: "productServiceEditorModal",
            innerProps: {
                onCreate: values =>
                    productServiceCrud.onCreate({ ...dealProduct, ...values }),
                excludeServiceIds,
                quantity: dealProduct.quantity,
                isEditing: false,
            },
            withCloseButton: false,
        });
    };

    const onDelete = productServiceCrud.onDelete;

    const isEmptyTable = dealProduct.productServices.length === 0;
    const isDuplicateServicesDisabled =
        dealProductsList.dealProducts.length <= 1;

    return {
        onChange,
        onCreate,
        onDelete,
        isEmptyTable,
        isDuplicateServicesDisabled,
    };
};

export default useProductServicesTable;
