import { ReceiptBox, ReceiptPallet, ReceiptProduct } from "../types/types.tsx";
import { ActionIcon, Divider, Group, NumberInput, rem, Stack, Text } from "@mantine/core";
import { IconTrash } from "@tabler/icons-react";

type Props = {
    products: ReceiptProduct[];
    object: ReceiptBox | ReceiptPallet;
    setObjectData: (object: ReceiptBox | ReceiptPallet) => void;
    disabled: boolean;
}

const ReceiptProducts = ({ products, object, setObjectData, disabled }: Props) => {
    if (products.length === 0) return;

    const deleteProduct = (productId: number) => {
        object.residualProducts = object.residualProducts.filter(product => product.id !== productId);
        setObjectData({ ...object });
    };

    const productQuantityInput = (receiptProduct: ReceiptProduct) => {
        return (
            <Group>
                <Text>Количество:</Text>
                <NumberInput
                    value={receiptProduct.quantity}
                    onChange={value => {
                        const idx = object.residualProducts.findIndex(p => p.id === receiptProduct.id);
                        object.residualProducts[idx].quantity = Number(value);
                        setObjectData({ ...object });
                    }}
                    min={1}
                    allowDecimal={false}
                    allowNegative={false}
                    w={rem(100)}
                    disabled={disabled}
                />
            </Group>
        );
    };

    return (
        <Stack>
            {products.map((receiptProduct: ReceiptProduct) => (
                <Stack key={receiptProduct.id}>
                    <Divider />
                    <Group wrap={"nowrap"} justify={"space-between"}>
                        <Stack gap={"sm"} key={`Product-${receiptProduct.id}`}>
                            <Text>Товар: {receiptProduct.product.name}</Text>
                            {productQuantityInput(receiptProduct)}
                            {receiptProduct.product.size && <Text>Размер: {receiptProduct.product.size}</Text>}
                        </Stack>
                        <ActionIcon
                            variant={"default"}
                            onClick={() => deleteProduct(receiptProduct.id)}
                            disabled={disabled}
                        >
                            <IconTrash />
                        </ActionIcon>
                    </Group>
                </Stack>
            ))}
        </Stack>
    );
};

export default ReceiptProducts;
