import { ProductSchema, ResidualBoxSchema, ResidualPalletSchema } from "../../../../client";
import { useState } from "react";
import { Button, Group, Radio, Stack, Text } from "@mantine/core";
import { notifications } from "../../../../shared/lib/notifications.ts";
import { ReceiptBox, ReceiptPallet } from "../NewReceipt/types/types.tsx";
import findProductInObject from "../NewReceipt/utils/findProductInObject.tsx";

type Props = {
    onProductSelect: (product?: ProductSchema) => void;
    isScanning: boolean;
    setIsScanning: (isScanning: boolean) => void;
    scannedValue: string;
    object: ReceiptBox | ReceiptPallet | ResidualPalletSchema | ResidualBoxSchema;
    barcodesProductsMap: Map<string, ProductSchema[]>;
}

const ScanBarcode = ({
                         onProductSelect,
                         isScanning,
                         setIsScanning,
                         scannedValue,
                         object,
                         barcodesProductsMap,
                     }: Props) => {

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

    const toggleScanning = () => {
        setIsScanning(!isScanning);
    };

    const renderScanningResults = () => {
        productsToSelect = barcodesProductsMap.get(scannedValue) ?? [];
        if (productsToSelect?.length === 0) {
            notifications.error({ message: `Товара с штрихкодом ${scannedValue} не найдено` });
            onProductSelect();
            return;
        }
        if (productsToSelect?.length === 1) {
            onProductSelect(productsToSelect[0]);
            return;
        }
        const product = findProductInObject(object, productsToSelect);
        if (product) {
            onProductSelect(product);
            return;
        }
        return renderProductSelect();
    };

    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>
        ));
    };

    const renderProductSelect = () => {
        return (
            <Stack>
                <Text>Выберите товар для данного штрихкода</Text>
                {renderProductsToSelect()}
                <Button
                    variant={"default"}
                    onClick={() => {
                        if (!selectedProduct) {
                            notifications.error({ message: "Товар не выбран" });
                        } else {
                            onProductSelect(selectedProduct);
                            setSelectedProduct(undefined);
                        }
                    }}
                >
                    Выбрать
                </Button>
            </Stack>
        );
    };

    return (scannedValue) ? (
        renderScanningResults()
    ) : (
        <Stack gap={0}>
            <Button
                variant={"default"}
                type={"button"}
                onClick={toggleScanning}
            >
                {isScanning ? "Отменить сканирование" : "Отсканировать штрихкод"}
            </Button>
        </Stack>
    );
};

export default ScanBarcode;
