import { useEffect, useState } from "react";
import { BoardSchema, BoardService } from "../../../../../client";
import { modals } from "@mantine/modals";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { useProjectsContext } from "../../../../../contexts/ProjectsContext.tsx";

type Props = {
    boards: BoardSchema[];
    refetchBoards: () => void;
}

const useBoards = ({ boards, refetchBoards }: Props) => {
    const [selectedBoard, setSelectedBoard] = useState<BoardSchema | null>(null);
    const { selectedProject: project } = useProjectsContext();

    useEffect(() => {
        if (boards.length > 0 && selectedBoard === null) {
            setSelectedBoard(boards[0]);
            return;
        }

        if (selectedBoard) {
            // Update selected board after changing all boards
            let newBoard = boards.find(board => board.id === selectedBoard.id);

            if (!newBoard && boards.length > 0) {
                newBoard = boards[0];
            }
            setSelectedBoard(newBoard ?? null);
        }
    }, [boards]);

    const onEditBoardClick = (board: BoardSchema) => {
        if (!project) return;
        modals.openContextModal({
            modal: "boardModal",
            title: "Редактирование доски",
            withCloseButton: false,
            innerProps: {
                projectId: project.id,
                board,
                refetchBoards,
            },
        });
    };

    const onCreateBoardClick = () => {
        if (!project) return;
        modals.openContextModal({
            modal: "boardModal",
            title: "Добавление доски",
            withCloseButton: false,
            innerProps: {
                projectId: project.id,
                refetchBoards,
            },
        });
    };

    const onDeleteBoardClick = (board: BoardSchema) => {
        if (!board) return;
        BoardService.deleteBoard({
            boardId: board.id,
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetchBoards();
            })
            .catch(err => console.log(err));
    };

    return {
        selectedBoard,
        setSelectedBoard,
        onCreateBoardClick,
        onEditBoardClick,
        onDeleteBoardClick,
    };
};

export default useBoards;
