import { ActionIcon, Divider, Flex, Group, rem, Stack, Text } from "@mantine/core";
import { ResidualBoxSchema, ResidualPalletSchema, ResidualProductSchema, ResiduesService } from "../../../../../client";
import { IconTrash } from "@tabler/icons-react";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import ProductQuantityField from "./ProductQuantityField.tsx";


type Props = {
    clientId: number | null;
    object: ResidualBoxSchema | ResidualPalletSchema | null;
    updateObject: () => void;
    disabled: boolean;
}

const ReceiptProducts = ({ clientId, object, updateObject, disabled }: Props) => {
    if (!object || !clientId) return;

    const deleteProduct = (residualProductId: number) => {
        ResiduesService.deleteResidualProduct({
            residualProductId,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                updateObject();
            })
            .catch(err => console.log(err));
    };

    const renderProducts = () => {
        return object.residualProducts
            .sort((a, b) => a.id - b.id)
            .map((residualProduct: ResidualProductSchema) => (
                <Stack key={residualProduct.id} gap={"sm"}>
                    <Divider />
                    <Group wrap={"nowrap"} justify={"space-between"}>
                        <Stack>
                            <Text>Товар: {residualProduct.product.name}</Text>
                            <ProductQuantityField
                                residualProduct={residualProduct}
                                updateObject={updateObject}
                                disabled={disabled}
                            />
                        </Stack>
                        <ActionIcon
                            variant={"default"}
                            onClick={() => deleteProduct(residualProduct.id)}
                            disabled={disabled}
                        >
                            <IconTrash />
                        </ActionIcon>
                    </Group>
                </Stack>
            ));
    };

    return (
        <Flex
            direction={"column"}
            gap={rem(10)}
        >
            {renderProducts()}
            <Divider />
        </Flex>
    );
};

export default ReceiptProducts;
