import { ContextModalProps } from "@mantine/modals";
import { Button, Group, Radio, Stack, Text } from "@mantine/core";
import { ProductSchema } from "../../../client";
import { notifications } from "../../../shared/lib/notifications.ts";
import { useState } from "react";


type Props = {
    productsToSelect: ProductSchema[];
    onProductSelect: (product: ProductSchema) => void;
}

const SelectScannedProductModal = ({
                                context,
                                id,
                                innerProps,
                            }: ContextModalProps<Props>) => {
    const {
        productsToSelect,
        onProductSelect,
    } = innerProps;

    const [selectedProduct, setSelectedProduct] = useState<ProductSchema>();

    const renderProductsToSelect = () => {
        return productsToSelect.map(product => (
            <Group key={product.id} wrap={"nowrap"}>
                <Radio
                    checked={selectedProduct?.id === product.id}
                    onChange={() => setSelectedProduct(product)}
                />
                <Stack>
                    <Text>{product.name}</Text>
                    {product.size && <Text>{product.size}</Text>}
                </Stack>
            </Group>
        ));
    };

    return (
        <Stack>
            {renderProductsToSelect()}
            <Button
                variant={"default"}
                onClick={() => {
                    if (!selectedProduct) {
                        notifications.error({ message: "Товар не выбран" });
                    } else {
                        onProductSelect(selectedProduct);
                        setSelectedProduct(undefined);
                        context.closeContextModal(id);
                    }
                }}
            >
                Выбрать
            </Button>
        </Stack>
    );
};

export default SelectScannedProductModal;
