import ObjectSelect, { ObjectSelectProps } from "../ObjectSelect/ObjectSelect.tsx";
import { FC, useEffect, useState } from "react";
import { ProjectSchema, ProjectService } from "../../client";

type OtherProps = {
    data?: ProjectSchema[];
}

type SelectProps = Omit<ObjectSelectProps<ProjectSchema | null>, "data" | "getLabelFn" | "getValueFn">;

type Props = OtherProps & SelectProps;

const ProjectSelect: FC<Props> = ({ data, ...props }) => {
    const [projects, setProjects] = useState<ProjectSchema[]>(data ?? []);

    const onClear = () => props.onChange(null);

    const fetchProjects = () => {
        ProjectService.getProjects()
            .then(({ projects }) => {
                setProjects(projects);
            })
            .catch(err => console.log(err));
    };

    useEffect(() => {
        if (!data) {
            fetchProjects();
        }
    }, []);

    return (
        <ObjectSelect
            data={projects}
            searchable
            placeholder={"Выберите проект"}
            onClear={onClear}
            {...props}
        />
    );
};

export default ProjectSelect;
