"use client";

import { Dispatch, SetStateAction } from "react";
import { UseFormReturnType } from "@mantine/form";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import useDealsAndGroups from "@/app/deals/hooks/useDealsAndGroups";
import { DealsFiltersForm } from "@/app/deals/hooks/useDealsFilters";
import useGroupDealsSelection, {
    GroupDealsSelection,
} from "@/app/deals/hooks/useGroupDealsSelection";
import useDealGroupCrud, { GroupsCrud } from "@/hooks/cruds/useDealGroupCrud";
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";
import GroupWithDealsSchema from "@/types/GroupWithDealsSchema";

type DealsContextState = {
    deals: DealSchema[];
    setDeals: (deals: DealSchema[]) => void;
    dealsWithoutGroup: DealSchema[];
    groupsWithDeals: GroupWithDealsSchema[];
    refetchDeals: () => void;
    dealsCrud: DealsCrud;
    groupsCrud: GroupsCrud;
    paginationInfo?: PaginationInfoSchema;
    page: number;
    setPage: Dispatch<SetStateAction<number>>;
    dealsFiltersForm: UseFormReturnType<DealsFiltersForm>;
    isChangedFilters: boolean;
    sortingForm: UseFormReturnType<SortingForm>;
    groupDealsSelection: GroupDealsSelection;
};

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,
        projectId,
        boardId,
        statuses,
    });

    const groupsCrud = useDealGroupCrud();

    const groupDealsSelection = useGroupDealsSelection({ groupsCrud });

    const { dealsWithoutGroup, groupsWithDeals } =
        useDealsAndGroups(dealsListObjects);

    return {
        ...dealsListObjects,
        dealsCrud,
        groupsCrud,
        dealsWithoutGroup,
        groupsWithDeals,
        groupDealsSelection,
    };
};

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