import { FC } from "react";
import ObjectSelect, {
    ObjectSelectProps,
} from "../../ObjectSelect/ObjectSelect.tsx";
import { ServiceSchema } from "../../../client";
import useServicesList from "../../../pages/ServicesPage/hooks/useServicesList.tsx";
import { omit } from "lodash";
import { ServiceType } from "../../../shared/enums/ServiceType.ts";
import { ComboboxItem, OptionsFilter } from "@mantine/core";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import { ComboboxParsedItemGroup } from "@mantine/core/lib/components/Combobox/Combobox.types";

type RestProps = {
    filterType?: ServiceType;
};
type Props = Omit<ObjectSelectProps<ServiceSchema>, "data"> & RestProps;
const ServiceSelectNew: FC<Props> = (props: Props) => {
    const { services } = useServicesList({ withPlaceholders: false });
    const data = props.filterType
        ? services.filter(service => service.serviceType === props.filterType)
        : services;

    const restProps = omit(props, ["filterType"]);
    const optionsFilter: OptionsFilter = ({ options, search }) => {
        return (options as ComboboxParsedItemGroup<ComboboxItem>[]).map(
            option => {
                return {
                    ...option,
                    items: option.items.filter((item: ComboboxItem) =>
                        item.label.toLowerCase().includes(search.toLowerCase()),
                    ),
                };
            },
        );
    };
    return (
        <ObjectSelect
            searchable
            {...restProps}
            data={data}
            groupBy={item => item.category.name}
            filter={optionsFilter}
        />
    );
};
export default ServiceSelectNew;
