"use client";

import React, { FC } from "react";
import { closestCorners, DndContext } from "@dnd-kit/core";
import {
    horizontalListSortingStrategy,
    SortableContext,
} from "@dnd-kit/sortable";
import { Group, ScrollArea } from "@mantine/core";
import DndOverlay from "@/app/deals/components/DndOverlay/DndOverlay";
import StatusColumn from "@/app/deals/components/StatusColumn/StatusColumn";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import useDealsAndStatusesDnd from "@/app/deals/hooks/useDealsAndStatusesDnd";
import { SortableItem } from "@/components/SortableDnd/SortableItem";
import useDndSensors from "../../hooks/useSensors";

type Props = {
    onDealDragEnd: (
        dealId: number,
        statusId: number,
        lexorank?: string
    ) => void;
    onStatusDragEnd: (statusId: number, lexorank: string) => void;
};

const StatusColumnsDnd: FC<Props> = props => {
    const { deals } = useStatusesContext();

    const {
        sortedStatuses,
        handleDragStart,
        handleDragOver,
        handleDragEnd,
        activeStatus,
        activeDeal,
    } = useDealsAndStatusesDnd(props);

    const sensors = useDndSensors();

    return (
        <ScrollArea
            offsetScrollbars={"x"}
            scrollbarSize={"0.5rem"}>
            <DndContext
                sensors={sensors}
                collisionDetection={closestCorners}
                onDragStart={handleDragStart}
                onDragOver={handleDragOver}
                onDragEnd={handleDragEnd}>
                <SortableContext
                    items={sortedStatuses.map(status => `${status.id}-status`)}
                    strategy={horizontalListSortingStrategy}>
                    <Group
                        gap={"xs"}
                        wrap={"nowrap"}
                        align={"start"}>
                        {sortedStatuses.map(status => (
                            <SortableItem
                                key={status.id}
                                id={`${status.id}-status`}>
                                <StatusColumn
                                    id={`${status.id}-status`}
                                    status={status}
                                    deals={deals}
                                    isDragging={activeStatus?.id === status.id}
                                />
                            </SortableItem>
                        ))}
                        <DndOverlay
                            activeStatus={activeStatus}
                            activeDeal={activeDeal}
                        />
                    </Group>
                </SortableContext>
            </DndContext>
        </ScrollArea>
    );
};

export default StatusColumnsDnd;
