"use client";

import React from "react";
import { Flex, ScrollArea } from "@mantine/core";
import Board from "@/app/deals/components/shared/Board/Board";
import CreateBoardButton from "@/app/deals/components/shared/CreateBoardButton/CreateBoardButton";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import SortableDnd from "@/components/dnd/SortableDnd";
import useHorizontalWheel from "@/hooks/utils/useHorizontalWheel";
import useIsMobile from "@/hooks/utils/useIsMobile";
import { BoardSchema } from "@/lib/client";
import styles from "./Boards.module.css";

const Boards = () => {
    const { boards, setSelectedBoardId, boardsCrud } = useBoardsContext();
    const isMobile = useIsMobile();
    const { ref, onWheel } = useHorizontalWheel<HTMLDivElement>();

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

    const onDragEnd = (itemId: number, newLexorank: string) => {
        boardsCrud.onUpdate(itemId, { lexorank: newLexorank });
    };

    const selectBoard = (board: BoardSchema) => {
        setSelectedBoardId(board.id);
    };

    return (
        <Flex
            align={"end"}
            className={styles.container}>
            <ScrollArea
                viewportRef={ref}
                onWheel={onWheel}
                offsetScrollbars={"x"}
                scrollbars={"x"}
                scrollbarSize={0}>
                <SortableDnd
                    initialItems={boards}
                    renderItem={renderBoard}
                    onDragEnd={onDragEnd}
                    onItemClick={selectBoard}
                    containerStyle={{ flexWrap: "nowrap" }}
                    dragHandleStyle={{ cursor: "pointer" }}
                    disabled={isMobile}
                />
            </ScrollArea>
            <CreateBoardButton />
        </Flex>
    );
};

export default Boards;
