import {Autocomplete, AutocompleteProps} from "@mantine/core";
import {useEffect, useMemo, useState} from "react";
import {ObjectWithNameAndId} from "../../types/utils.ts";
import {omit} from "lodash";


export type AutocompleteObjectType<T extends ObjectWithNameAndId> = T;

type ControlledValueProps<T extends ObjectWithNameAndId> = {
    value: AutocompleteObjectType<T>,
    onChange: (value: string) => void;
}

type RestProps<T extends ObjectWithNameAndId> = {
    defaultValue?: AutocompleteObjectType<T>
    onChange: (value: string) => void;
    data: AutocompleteObjectType<T>[];
    filterBy?: (item: AutocompleteObjectType<T>) => boolean;
}

export type ObjectAutocompleteProps<T extends ObjectWithNameAndId> =
    (RestProps<T> & Partial<ControlledValueProps<T>>)
    & Omit<AutocompleteProps, 'value' | 'onChange' | 'data'>;

const ObjectAutocomplete = <T extends ObjectWithNameAndId, >(props: ObjectAutocompleteProps<T>) => {

    const isControlled = 'value' in props;
    const [internalValue, setInternalValue] = useState<undefined | string>(props.defaultValue);

    const value = isControlled ? props.value?.name : internalValue;

    const data = useMemo(() => {
        const propsData = props.filterBy ? props.data.filter(props.filterBy) : props.data;

        return propsData.map(item => ({
            label: item.name,
            value: item.id.toString()
        }));
    }, [props.data]);

    const handleOnChange = (event: string | null) => {
        if (!event) return;
        if (isControlled) {
            props.onChange(event);
            return;
        }
        setInternalValue(event);
    }

    useEffect(() => {
        if (isControlled || !internalValue) return;
        props.onChange(internalValue);
    }, [internalValue]);
    const restProps = omit(props, ['filterBy', 'groupBy']);
    return (
        <Autocomplete
            {...restProps}
            value={value?.toString()}
            onChange={handleOnChange}
            data={data}
        />
    )
}

export default ObjectAutocomplete;