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

type OtherProps = {
    project: ProjectSchema | null;
}

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

type Props = OtherProps & SelectProps;

const BoardSelect: FC<Props> = ({ project, ...props }) => {
    const [boards, setBoards] = useState<BoardSchema[]>([]);
    const [isInitial, setIsInitial] = useState<boolean>(true);

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

    const fetchBoards = () => {
        if (!project?.id) {
            setBoards([]);
            return;
        }

        BoardService.getBoards({
            projectId: project?.id,
        })
            .then(({ boards }) => {
                setBoards(boards);
            })
            .catch(err => console.log(err));
    };

    useEffect(() => {
        fetchBoards();
        if (isInitial) {
            setIsInitial(false);
        } else {
            onClear();
        }
    }, [project?.id]);

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

export default BoardSelect;
