import { ProductSchema } from "../../../client";
import { ComboboxItem, ComboboxLikeRenderOptionInput, Image, rem, SelectProps, Text, Tooltip } from "@mantine/core";
import { getProductFields } from "../../../types/utils.ts";

const getRenderOptions = (products: ProductSchema[]): SelectProps["renderOption"] => {
    return (item: ComboboxLikeRenderOptionInput<ComboboxItem>) => {
        const product = products.find(
            product => product.id == parseInt(item.option.value),
        );
        if (!product) return item.option.label;
        const productFields = getProductFields(product);
        const imageUrl =
            product.images && product.images[0]
                ? product.images[0].imageUrl
                : undefined;

        return (
            <Tooltip
                style={{ whiteSpace: "pre-line" }}
                multiline
                disabled={productFields.length === 0}
                label={
                    <>
                        {productFields
                            .map(([key, value]) => {
                                return `${key.toString()}: ${value.toString()}`;
                            })
                            .join("\n")}
                        {imageUrl && (
                            <Image
                                src={imageUrl}
                                alt={product.name}
                                maw={rem(250)}
                            />
                        )}
                    </>
                }>
                <div>
                    {product.name}
                    <br />
                    {product.barcodes && (
                        <Text size={"xs"}>{product.barcodes[0]}</Text>
                    )}
                </div>
            </Tooltip>
        );
    };
};

export default getRenderOptions;
