import {Select, SelectProps} from "@mantine/core";
import useServiceCategoriesList from "../../hooks/useServiceCategoriesList.tsx";
import {ServiceCategorySchema} from "../../../../client";
import {FC, useEffect, useMemo, useState} from "react";

type ControlledValueProps = {
    value: ServiceCategorySchema
    onChange: (value: ServiceCategorySchema) => void
}

type RestProps = {
    fullWidth?: boolean,
    defaultValue?: ServiceCategorySchema
    onChange: (category: ServiceCategorySchema) => void
}
type Props = (RestProps & Partial<ControlledValueProps>) & Omit<SelectProps, 'value' | 'onChange'>;
const ServiceCategorySelect: FC<Props> = (props: Props) => {
    const {categories} = useServiceCategoriesList();

    const data = useMemo(() => categories.reduce((acc, category) => {
        acc.push({
            label: category.name,
            value: category.id.toString()
        });
        return acc;
    }, [] as { label: string, value: string }[]), [categories]);

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

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

    useEffect(() => {
        if (isControlled || !internalValue) return;
        props.onChange(internalValue);
    }, [internalValue]);
    return (
        <Select
            {...props}
            value={value?.id.toString()}
            onChange={handleOnChange}
            data={data}
        />
    )
}

export default ServiceCategorySelect;