"use client";

import React, { FC, ReactNode } from "react";
import { IconChevronLeft, IconGripVertical } from "@tabler/icons-react";
import { Box, Center, Divider, Drawer, Group, rem, Text } from "@mantine/core";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import BoardMobile from "@/app/deals/drawers/ProjectBoardsEditorDrawer/components/BoardMobile";
import CreateBoardButton from "@/app/deals/drawers/ProjectBoardsEditorDrawer/components/CreateBoardButton";
import SortableDnd from "@/components/dnd/SortableDnd";
import { BoardSchema } from "@/lib/client";

const ProjectBoardsEditorDrawer: FC = () => {
    const {
        boards,
        onUpdateBoard,
        isEditorDrawerOpened,
        setIsEditorDrawerOpened,
    } = useBoardsContext();
    const { selectedProject } = useProjectsContext();
    const onClose = () => setIsEditorDrawerOpened(false);

    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) => {
        onUpdateBoard(itemId, { lexorank: newLexorank });
    };

    return (
        <Drawer
            size={"100%"}
            position={"right"}
            onClose={onClose}
            removeScrollProps={{ allowPinchZoom: true }}
            withCloseButton={false}
            opened={isEditorDrawerOpened}
            trapFocus={false}
            styles={{
                body: {
                    height: "100%",
                    display: "flex",
                    flexDirection: "column",
                    gap: rem(10),
                },
            }}>
            <Group justify={"space-between"}>
                <Box
                    onClick={onClose}
                    p={"xs"}>
                    <IconChevronLeft />
                </Box>
                <Center>
                    <Text>{selectedProject?.name}</Text>
                </Center>
                <Box p={"lg"} />
            </Group>
            <Divider />
            <SortableDnd
                initialItems={boards}
                onDragEnd={onDragEnd}
                renderItem={renderBoard}
                renderDraggable={renderDraggable}
                dragHandleStyle={{ width: "auto" }}
                vertical
            />
            <CreateBoardButton />
        </Drawer>
    );
};

export default ProjectBoardsEditorDrawer;
