import { BoardSchema, CardSummary, StatusSchema } from "../../../../client";
import CardsDndColumn from "../../Cards/CardsDndColumn/CardsDndColumn.tsx";
import styles from "../../../../pages/CardsPage/ui/CardsPage.module.css";
import CardsDndFooter from "../../Cards/CardsDndFooter/CardsDndFooter.tsx";
import { Flex, rem, Stack } from "@mantine/core";
import { DragDropContext } from "@hello-pangea/dnd";
import useDnd from "../../../../pages/CardsPage/hooks/useDnd.tsx";
import Status from "../Status/Status.tsx";


type Props = {
    selectedBoard: BoardSchema | null;
    summariesRaw: CardSummary[];
    refetchSummaries: () => void;
    refetchBoards: () => void;
}

const Statuses = ({
                      selectedBoard,
                      summariesRaw,
                      refetchSummaries,
                      refetchBoards,
                  }: Props) => {
    const {
        summaries,
        dragState,
        onDragStart,
        onDragEnd,
    } = useDnd({
        selectedBoard,
        summariesRaw,
        refetchSummaries,
        refetchBoards,
    });

    const statusDndColumn = (status: StatusSchema, index: number) => {
        const filteredSummaries = summaries.filter(
            summary => summary.status.id == status.id,
        );

        return (
            <Stack key={status.id} gap={0} flex={1} maw={rem(250)}>
                <Status
                    summaries={filteredSummaries}
                    index={index}
                    status={status}
                    board={selectedBoard}
                    dragState={dragState}
                    refetch={refetchBoards}
                />
                <CardsDndColumn
                    withCreateButton={index === 0}
                    summaries={filteredSummaries}
                    status={status}
                    dragState={dragState}
                />
            </Stack>
        );
    };

    const statuses = selectedBoard?.statuses
        .filter(status => !status.isDeleted)
        .sort((a, b) => a.ordinalNumber - b.ordinalNumber) ?? [];

    return (
        <DragDropContext
            onDragStart={onDragStart}
            onDragEnd={onDragEnd}
        >
            <Flex
                justify={"space-between"}
                direction={"column"}
            >
                <Flex className={styles["statuses"]}>
                    {selectedBoard &&
                        statuses.map(((status: StatusSchema, index: number) => {
                            return statusDndColumn(status, index);
                        }))
                    }
                </Flex>
                <CardsDndFooter dragState={dragState} />
            </Flex>
        </DragDropContext>
    );
};

export default Statuses;
