"use client";

import React from "react";
import { useMutation } from "@tanstack/react-query";
import { Group, ScrollArea } from "@mantine/core";
import Board from "@/app/deals/components/Board/Board";
import CreateBoardButton from "@/app/deals/components/CreateBoardButton/CreateBoardButton";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import SortableDnd from "@/components/dnd/SortableDnd";
import { BoardSchema } from "@/lib/client";
import { updateBoardMutation } from "@/lib/client/@tanstack/react-query.gen";
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%"}>
            <Group wrap={"nowrap"}>
                <SortableDnd
                    initialItems={boards}
                    renderItem={renderBoard}
                    onDragEnd={onDragEnd}
                    onItemClick={selectBoard}
                    rowStyle={{ flexWrap: "nowrap" }}
                />
                <CreateBoardButton />
            </Group>
        </ScrollArea>
    );
};

export default Boards;
