import {ServiceSchema} from "../../client";
import {FC, useEffect, useMemo, useState} from "react";
import {Select, SelectProps} from "@mantine/core";
import useServicesList from "../../pages/ServicesPage/hooks/useServicesList.tsx";

type ControlledValueProps = {
    value: ServiceSchema;
    onChange: (value: ServiceSchema) => void;
}
type RestProps = {
    defaultValue?: ServiceSchema;
    onChange: (value: ServiceSchema) => void;
}
type Props = (RestProps & Partial<ControlledValueProps>) & Omit<SelectProps, 'value' | 'onChange'>;


const ServiceSelect: FC<Props> = (props) => {
    const isControlled = props.value !== undefined;
    const [internalValue, setInternalValue] = useState<ServiceSchema | undefined>(props.defaultValue);
    const value = isControlled ? props.value : internalValue;
    const {services} = useServicesList();
    const categories = useMemo(() => services.reduce((acc, service) => {
        if (!acc.includes(service.category.name)) {
            acc.push(service.category.name);
        }
        return acc;
    }, [] as string[]), [services]);

    const data = useMemo(() => categories.map(category => ({
        group: category,
        items: services.filter(service => service.category.name === category)
            .map(service => ({
                value: service.id.toString(),
                label: service.name
            }))
    })), [services, categories]);


    const handleOnChange = (value: string) => {
        if (isControlled) {
            props.onChange(services.find(service => service.id.toString() === value) as ServiceSchema);
            return;
        }
        setInternalValue(services.find(service => service.id.toString() === value) as ServiceSchema);
    }
    useEffect(() => {
        if (!isControlled) {
            props.onChange(internalValue as ServiceSchema);
        }
    }, [internalValue]);
    return (
        <Select
            {...props}
            value={value?.id.toString()}
            withCheckIcon={false}
            searchable
            onChange={event => event && handleOnChange(event)}
            data={data}
        />
    )
}

export default ServiceSelect;