import React, { ReactNode } from "react";
import { useDroppable } from "@dnd-kit/core";
import {
    SortableContext,
    verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { Stack } from "@mantine/core";
import { getDndGroupId } from "@/components/dnd/FunnelDnd/utils/groupId";
import SortableItem from "@/components/dnd/SortableItem";
import {
    BaseDraggable,
    BaseGroupDraggable,
} from "@/components/dnd/types/types";
import isItemGroup from "@/app/deals/utils/isItemGroup";

type Props<
    TItem extends BaseDraggable,
    TGroup extends BaseGroupDraggable<TItem>,
> = {
    id: string;
    itemsAndGroups: (TItem | TGroup)[];
    renderItem: (item: TItem) => ReactNode;
    renderGroup: (group: TGroup) => ReactNode;
    children?: ReactNode;
};

const FunnelColumn = <
    TItem extends BaseDraggable,
    TGroup extends BaseGroupDraggable<TItem>,
>({
    id,
    itemsAndGroups,
    renderItem,
    renderGroup,
    children,
}: Props<TItem, TGroup>) => {
    const { setNodeRef } = useDroppable({ id });

    return (
        <>
            {children}
            <SortableContext
                id={id}
                items={itemsAndGroups.map(itemOrGroup =>
                    isItemGroup(itemOrGroup)
                        ? getDndGroupId(itemOrGroup.id)
                        : itemOrGroup.id
                )}
                strategy={verticalListSortingStrategy}>
                <Stack
                    gap="xs"
                    ref={setNodeRef}>
                    {itemsAndGroups.map(itemOrGroup =>
                        "items" in itemOrGroup ? (
                            <SortableItem
                                key={`${itemOrGroup.id.toString()}g`}
                                dragHandleStyle={{ cursor: "pointer" }}
                                id={getDndGroupId(itemOrGroup.id)}
                                renderItem={() => renderGroup(itemOrGroup)}
                            />
                        ) : (
                            <SortableItem
                                key={itemOrGroup.id}
                                dragHandleStyle={{ cursor: "pointer" }}
                                id={itemOrGroup.id}
                                renderItem={() => renderItem(itemOrGroup)}
                            />
                        )
                    )}
                </Stack>
            </SortableContext>
        </>
    );
};

export default FunnelColumn;
