"use client";

import React from "react";
import { useMutation } from "@tanstack/react-query";
import { ScrollArea } from "@mantine/core";
import Board from "@/app/deals/components/Board/Board";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { BoardSchema } from "@/client";
import { updateBoardMutation } from "@/client/@tanstack/react-query.gen";
import SortableDnd from "@/components/SortableDnd";
import { notifications } from "@/lib/notifications";

const Boards = () => {
    const { boards, setSelectedBoard, refetchBoards } = useBoardsContext();

    const updateBoard = useMutation({
        ...updateBoardMutation(),
        onError: error => {
            console.error(error);
            notifications.error({
                message: error.response?.data?.detail as string | undefined,
            });
            refetchBoards();
        },
    });

    const renderBoard = (board: BoardSchema) => {
        return <Board board={board} />;
    };

    const onDragEnd = (itemId: number, newLexorank: string) => {
        updateBoard.mutate({
            path: {
                boardId: itemId,
            },
            body: {
                board: {
                    lexorank: newLexorank,
                },
            },
        });
    };

    const selectBoard = (board: BoardSchema) => {
        setSelectedBoard(board);
    };

    return (
        <ScrollArea
            offsetScrollbars={"x"}
            scrollbars={"x"}
            scrollbarSize={0}
            w={"100%"}>
            <SortableDnd
                initialItems={boards}
                renderItem={renderBoard}
                onDragEnd={onDragEnd}
                onItemClick={selectBoard}
                rowStyle={{ flexWrap: "nowrap" }}
            />
        </ScrollArea>
    );
};

export default Boards;
