"use client";

import React, { FC } from "react";
import { IconChevronLeft } from "@tabler/icons-react";
import { Box, Center, Drawer, Group, rem, Text } from "@mantine/core";
import Board from "@/app/deals/components/Board/Board";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import CreateBoardButtonMobile from "@/app/deals/drawers/ProjectBoardsEditorDrawer/components/CreateBoardButtonMobile";
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 renderBoard = (board: BoardSchema) => {
        return <Board board={board} />;
    };

    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}
            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>
            <SortableDnd
                initialItems={boards}
                renderItem={renderBoard}
                onDragEnd={onDragEnd}
                vertical
            />
            <CreateBoardButtonMobile />
        </Drawer>
    );
};

export default ProjectBoardsEditorDrawer;
