import {
    Box,
    ComboboxItem,
    ComboboxLikeRenderOptionInput,
    Image,
    rem,
    SelectProps,
    Stack,
    Text,
    Tooltip,
} from "@mantine/core";
import { ProductSchema } from "@/lib/client";
import ProductFieldsList from "@/modules/dealModularEditorTabs/FulfillmentBase/desktop/components/ProductView/components/ProductFieldsList";
import getProductFieldList from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/components/ProductSelect/utils/getProductFieldList";

const renderProductOption = (
    products: ProductSchema[]
): SelectProps["renderOption"] => {
    return (item: ComboboxLikeRenderOptionInput<ComboboxItem>) => {
        const product = products.find(
            product => product.id === Number(item.option.value)
        );
        if (!product) return item.option.label;

        const fieldsList = getProductFieldList(product);

        return (
            <Tooltip
                style={{ whiteSpace: "pre-line" }}
                multiline
                disabled={fieldsList.length === 0 && !product.imageUrl}
                label={
                    <Stack
                        gap={"xs"}
                        maw={rem(250)}>
                        <ProductFieldsList product={product} />
                        {product.imageUrl && (
                            <Image
                                src={product.imageUrl}
                                alt={product.name}
                                maw={rem(250)}
                            />
                        )}
                    </Stack>
                }>
                <Box w={"100%"}>
                    {product.name}
                    <br />
                    {product.barcodes && (
                        <Text size={"xs"}>{product.barcodes[0]}</Text>
                    )}
                </Box>
            </Tooltip>
        );
    };
};

export default renderProductOption;
