import { DropResult } from "@hello-pangea/dnd";
import { BoardSchema, BoardService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { useState } from "react";


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

const useBoardsDnd = ({ boards, refetchBoards }: Props) => {
    const [isBoardDragEnded, setIsBoardDragEnded] = useState(true);

    const updateBoardOrder = (board: BoardSchema, newOrdinalNumber: number) => {
        BoardService.updateBoardOrder({
            requestBody: {
                projectId: board.projectId,
                boardId: board.id,
                newOrdinalNumber,
            }
        })
            .then(({ ok, message }) => {
                if (!ok) notifications.error({ message });
                refetchBoards();
            })
    };

    const onBoardDragEnd = async (result: DropResult) => {
        setIsBoardDragEnded(true);

        // If there is no changes
        if (!result.destination || result.destination == result.source) return;

        // Checking for valid cardId
        const boardId = parseInt(result.draggableId);
        if (isNaN(boardId)) return;

        // Checking for valid card
        const board = boards.find(board => board.id == boardId);
        if (!board) return;

        updateBoardOrder(board, result.destination.index);
    };

    return {
        onBoardDragEnd,
        isBoardDragEnded,
        setIsBoardDragEnded,
    };
};

export default useBoardsDnd;
