"use client";

import { useMutation } from "@tanstack/react-query";
import StatusColumnsDnd from "@/app/deals/components/StatusColumnsDnd/StatusColumnsDnd";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import {
    updateDealMutation,
    updateStatusMutation,
} from "@/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

const StatusColumns = () => {
    const { refetchStatuses, refetchDeals } = useStatusesContext();

    const updateStatus = useMutation({
        ...updateStatusMutation(),
        onError: error => {
            console.error(error);
            notifications.error({
                message: error.response?.data?.detail as string | undefined,
            });
            refetchStatuses();
        },
    });

    const updateDeals = useMutation({
        ...updateDealMutation(),
        onError: error => {
            console.error(error);
            notifications.error({
                message: error.response?.data?.detail as string | undefined,
            });
            refetchDeals();
        },
    });

    const onDealDragEnd = (
        dealId: number,
        statusId: number,
        lexorank?: string
    ) => {
        updateDeals.mutate({
            path: {
                dealId,
            },
            body: {
                deal: {
                    statusId,
                    lexorank,
                },
            },
        });
    };

    const onStatusDragEnd = (statusId: number, lexorank: string) => {
        updateStatus.mutate({
            path: {
                statusId,
            },
            body: {
                status: {
                    lexorank,
                },
            },
        });
    };

    return (
        <StatusColumnsDnd
            onDealDragEnd={onDealDragEnd}
            onStatusDragEnd={onStatusDragEnd}
        />
    );
};

export default StatusColumns;
