import React, { FC, ReactNode } from "react";
import { IconChevronLeft, IconGripVertical } from "@tabler/icons-react";
import { Box, Center, Divider, Group, Text } from "@mantine/core";
import BoardMobile from "@/app/deals/drawers/BoardsMobileEditorDrawer/components/BoardMobile";
import CreateBoardButton from "@/app/deals/drawers/BoardsMobileEditorDrawer/components/CreateBoardButton";
import { useBoardsMobileContext } from "@/app/deals/drawers/BoardsMobileEditorDrawer/contexts/BoardsMobileContext";
import SortableDnd from "@/components/dnd/SortableDnd";
import { BoardSchema } from "@/lib/client";

type Props = {
    onClose: () => void;
};

const BoardsDrawerBody: FC<Props> = ({ onClose }) => {
    const { boards, boardsCrud, project } = useBoardsMobileContext();

    const renderDraggable = () => (
        <Box p={"xs"}>
            <IconGripVertical />
        </Box>
    );

    const renderBoard = (
        board: BoardSchema,
        renderDraggable?: (item: BoardSchema) => ReactNode
    ) => {
        return (
            <Group wrap={"nowrap"}>
                {renderDraggable && renderDraggable(board)}
                <BoardMobile board={board} />
            </Group>
        );
    };

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

    return (
        <>
            <Group justify={"space-between"}>
                <Box
                    onClick={onClose}
                    p={"xs"}>
                    <IconChevronLeft />
                </Box>
                <Center>
                    <Text>{project.name}</Text>
                </Center>
                <Box p={"lg"} />
            </Group>
            <Divider />
            <SortableDnd
                initialItems={boards}
                onDragEnd={onDragEnd}
                renderItem={renderBoard}
                renderDraggable={renderDraggable}
                dragHandleStyle={{ width: "auto" }}
                vertical
            />
            <CreateBoardButton onCreateBoard={boardsCrud.onCreate} />
        </>
    );
};

export default BoardsDrawerBody;
