import React, { FC, ReactNode } from "react";
import { IconChevronLeft, IconGripVertical } from "@tabler/icons-react";
import { Box, Center, Divider, Group, Text } from "@mantine/core";
import CreateStatusButton from "@/app/deals/drawers/BoardStatusesEditorDrawer/components/CreateStatusButton";
import StatusMobile from "@/app/deals/drawers/BoardStatusesEditorDrawer/components/StatusMobile";
import { useBoardStatusesContext } from "@/app/deals/drawers/BoardStatusesEditorDrawer/contexts/BoardStatusesContext";
import SortableDnd from "@/components/dnd/SortableDnd";
import { StatusSchema } from "@/lib/client";

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

const StatusesDrawerBody: FC<Props> = ({ onClose }) => {
    const { onUpdateStatus, board, statuses } = useBoardStatusesContext();

    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}
                    board={board}
                />
            </Group>
        );
    };

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

    return (
        <>
            <Group justify={"space-between"}>
                <Box
                    onClick={onClose}
                    p={"xs"}>
                    <IconChevronLeft />
                </Box>
                <Center>
                    <Text>{board.name}</Text>
                </Center>
                <Box p={"lg"} />
            </Group>
            <Divider />
            <SortableDnd
                initialItems={statuses}
                onDragEnd={onDragEnd}
                renderItem={renderStatus}
                renderDraggable={renderDraggable}
                dragHandleStyle={{ width: "auto" }}
                vertical
            />
            <CreateStatusButton />
        </>
    );
};

export default StatusesDrawerBody;
