import { FC } from "react";
import { omit } from "lodash";
import {
    ComboboxItem,
    ComboboxParsedItemGroup,
    OptionsFilter,
} from "@mantine/core";
import ObjectSelect, {
    ObjectSelectProps,
} from "@/components/selects/ObjectSelect/ObjectSelect";
import { ServiceSchema } from "@/lib/client";
import useServicesList from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useServicesList";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";

type RestProps = {
    filterType?: ServiceType;
};

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

const ServiceSelect: FC<Props> = props => {
    const { services } = useServicesList();
    const data =
        props.filterType !== undefined
            ? services.filter(
                  service => service.serviceType === props.filterType
              )
            : services;

    const restProps = omit(props, ["filterType"]);

    const optionsFilter: OptionsFilter = ({ options, search }) => {
        return (options as ComboboxParsedItemGroup[]).map(option => {
            return {
                ...option,
                items: option.items.filter((item: ComboboxItem) =>
                    item.label.toLowerCase().includes(search.toLowerCase())
                ),
            };
        });
    };

    return (
        <ObjectSelect
            {...restProps}
            data={data}
            searchable
            groupBy={service => service.category.name}
            filter={optionsFilter}
        />
    );
};

export default ServiceSelect;
