import { BoardSchema, CardSummary } from "../../../client";
import { DragStart, DropResult } from "@hello-pangea/dnd";
import { useState } from "react";
import DragState from "../enums/DragState.ts";
import useCardsDnd from "../../../components/Dnd/Cards/CardsDndColumn/hooks/useCardsDnd.tsx";
import useStatusesDnd from "../../../components/Dnd/Statuses/Statuses/hooks/useStatusesDnd.tsx";


type Props = {
    selectedBoard: BoardSchema | null;
    summariesRaw: CardSummary[];
    refetchSummaries: () => void;
    refetchBoards: () => void;
}

const useDnd = ({
                    selectedBoard,
                    summariesRaw,
                    refetchSummaries,
                    refetchBoards,
                }: Props) => {
    const [dragState, setDragState] = useState<DragState>(DragState.DRAG_ENDED);

    const {
        summaries,
        onCardDragEnd,
    } = useCardsDnd({
        summariesRaw,
        refetchSummaries,
    })

    const {
        onStatusDragEnd,
    } = useStatusesDnd({
        board: selectedBoard,
        refetch: refetchBoards,
    });

    const onDragEnd = async (result: DropResult) => {
        setDragState(DragState.DRAG_ENDED);
        if (result.draggableId.includes("status")) {
            return onStatusDragEnd(result);
        }
        return onCardDragEnd(result);
    }

    const onDragStart = (start: DragStart) => {
        if (start.source.droppableId.includes("status")) {
            setDragState(DragState.DRAG_STATUS);
        } else {
            setDragState(DragState.DRAG_CARD);
        }
    }

    return {
        summaries,
        dragState,
        onDragStart,
        onDragEnd,
    };
};

export default useDnd;
