"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 { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import CreateStatusButton from "@/app/deals/drawers/BoardStatusesEditorDrawer/components/CreateStatusButton";
import StatusMobile from "@/app/deals/drawers/BoardStatusesEditorDrawer/components/StatusMobile";
import SortableDnd from "@/components/dnd/SortableDnd";
import { StatusSchema } from "@/lib/client";

const BoardStatusesEditorDrawer: FC = () => {
    const {
        statuses,
        onUpdateStatus,
        isEditorDrawerOpened,
        setIsEditorDrawerOpened,
    } = useStatusesContext();
    const { selectedBoard } = useBoardsContext();
    const onClose = () => setIsEditorDrawerOpened(false);

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

    const renderStatus = (
        status: StatusSchema,
        renderDraggable?: (item: StatusSchema) => ReactNode
    ) => {
        return (
            <Group wrap={"nowrap"}>
                {renderDraggable && renderDraggable(status)}
                <StatusMobile status={status} />
            </Group>
        );
    };

    const onDragEnd = (itemId: number, newLexorank: string) => {
        onUpdateStatus(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>{selectedBoard?.name}</Text>
                </Center>
                <Box p={"lg"} />
            </Group>
            <Divider />
            <SortableDnd
                initialItems={statuses}
                onDragEnd={onDragEnd}
                renderItem={renderStatus}
                renderDraggable={renderDraggable}
                dragHandleStyle={{ width: "auto" }}
                vertical
            />
            <CreateStatusButton />
        </Drawer>
    );
};

export default BoardStatusesEditorDrawer;
