import { Group, NumberInput, rem, Text } from "@mantine/core";
import { ResidualProductSchema, ResiduesService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";

type Props = {
    residualProduct: ResidualProductSchema;
    updateObject: () => void;
    disabled: boolean;
}

const ProductQuantityField = ({ residualProduct, updateObject, disabled }: Props) => {
    const updateProduct = (quantity: number) => {
        if (residualProduct.quantity === quantity) return;
        ResiduesService.updateResidualProduct({
            requestBody: {
                data: {
                    quantity,
                    productId: residualProduct.product.id,
                },
            },
            residualProductId: residualProduct.id,
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                }
                updateObject();
            })
            .catch(err => console.log(err));
    };

    return (
        <Group>
            <Text>Количество: </Text>
            <NumberInput
                value={residualProduct.quantity}
                onChange={(value) => updateProduct(Number(value))}
                min={1}
                allowDecimal={false}
                allowNegative={false}
                w={rem(100)}
                disabled={disabled}
            />
        </Group>
    );
};

export default ProductQuantityField;
