import { modals } from "@mantine/modals";
import { useProductsContext } from "@/app/products/contexts/ProductsContext";
import { ProductSchema } from "@/lib/client";
import { notifications } from "@/lib/notifications";

const useProductsActions = () => {
    const { productsCrud, productsFiltersForm, refetch } = useProductsContext();

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

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

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

    const onPrintBarcodeClick = (product: ProductSchema) => {
        modals.openContextModal({
            modal: "printBarcodeModal",
            title: "Печать штрихкода",
            withCloseButton: true,
            innerProps: {
                product,
                defaultQuantity: 1,
            },
        });
    };

    return {
        onCreateClick,
        onChangeClick,
        onPrintBarcodeClick,
    };
};

export default useProductsActions;
