import { useEffect, useState } from "react";
import { omit } from "lodash";
import ObjectSelect from "@/components/selects/ObjectSelect/ObjectSelect";
import useAttributeOptionsList from "@/hooks/lists/useAttributeOptionsList";
import { AttrOptionSchema } from "@/lib/client";

type Props = {
    value: number;
    onChange: (val: any) => void;
    selectId: number;
    error?: string;
    label?: string;
};

const AttrOptionSelect = (props: Props) => {
    const { options } = useAttributeOptionsList(props);

    const [selectedOption, setSelectedOption] = useState<AttrOptionSchema>();

    useEffect(() => {
        if (!props.value) {
            setSelectedOption(undefined);
            return;
        }
        setSelectedOption(options.find(option => option.id === props.value));
    }, [props.value, options]);

    const restProps = omit(props, ["value, onChange", "selectId"]);

    return (
        <ObjectSelect
            label={"Значение"}
            {...restProps}
            data={options}
            value={selectedOption}
            onChange={option => {
                setSelectedOption(option);
                props.onChange(option.id);
            }}
            onClear={() => {
                setSelectedOption(undefined);
                props.onChange(null);
            }}
            getLabelFn={option => option.label}
            clearable
            searchable
        />
    );
};

export default AttrOptionSelect;
