"use client";

import React from "react";
import { UseFormReturnType } from "@mantine/form";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import { DealsFiltersForm } from "@/app/deals/hooks/useDealsFilters";
import { DealsCrud, useDealsCrud } from "@/hooks/cruds/useDealsCrud";
import useDealsList from "@/hooks/lists/useDealsList";
import { SortingForm } from "@/hooks/utils/useSorting";
import { DealSchema, PaginationInfoSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

type DealsContextState = {
    deals: DealSchema[];
    setDeals: (deals: DealSchema[]) => void;
    refetchDeals: () => void;
    dealsCrud: DealsCrud;
    paginationInfo?: PaginationInfoSchema;
    page: number;
    setPage: React.Dispatch<React.SetStateAction<number>>;
    dealsFiltersForm: UseFormReturnType<DealsFiltersForm>;
    isChangedFilters: boolean;
    sortingForm: UseFormReturnType<SortingForm>;
};

type Props = {
    withPagination?: boolean;
    boardId?: number;
    projectId?: number;
};

const useDealsContextState = ({
    boardId,
    projectId,
    withPagination = false,
}: Props): DealsContextState => {
    const { statuses } = useStatusesContext();

    const dealsListObjects = useDealsList({
        boardId,
        projectId,
        withPagination,
    });

    const dealsCrud = useDealsCrud({
        ...dealsListObjects,
        boardId,
        statuses,
    });

    return {
        ...dealsListObjects,
        dealsCrud,
    };
};

export const [DealsContextProvider, useDealsContext] = makeContext<
    DealsContextState,
    Props
>(useDealsContextState, "Deals");
