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

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

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

    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) =>
        statusesCrud.onUpdate(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;
