import { FC, useState } from "react";
import { omit } from "lodash";
import { Loader, OptionsFilter } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import ObjectSelect, {
    ObjectSelectProps,
} from "@/components/selects/ObjectSelect/ObjectSelect";
import { ProductSchema } from "@/lib/client";
import useProductsList from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useProductsList";
import renderProductOption from "./utils/renderProductOption";

type RestProps = {
    clientId: number;
};

const MAX_PRODUCTS = 200;

type Props = Omit<ObjectSelectProps<ProductSchema>, "data"> & RestProps;

const ProductSelect: FC<Props> = (props: Props) => {
    const [searchValue, setSearchValue] = useState("");
    const [debounced] = useDebouncedValue(searchValue, 500);
    const { products, isLoading } = useProductsList({
        // clientId: props.clientId,
        searchInput: debounced,
        page: 0,
        itemsPerPage: MAX_PRODUCTS,
    });
    const restProps = omit(props, ["clientId"]);

    const optionsFilter: OptionsFilter = ({ options }) => options;
    const setSearchValueImpl = (value: string) => {
        const names = products.map(product => product.name);
        if (names.includes(value)) return;
        setSearchValue(value);
    };

    return (
        <ObjectSelect
            rightSection={
                isLoading || searchValue !== debounced ? (
                    <Loader size={"sm"} />
                ) : null
            }
            onSearchChange={setSearchValueImpl}
            renderOption={renderProductOption(products)}
            searchable
            {...restProps}
            data={products}
            filter={optionsFilter}
        />
    );
};

export default ProductSelect;
