"use client";

import { useForm, UseFormReturnType } from "@mantine/form";
import { useDebouncedValue } from "@mantine/hooks";
import { ClientSchema, PaginationInfoSchema, ProductSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";
import {
    ProductsCrud,
    useProductsCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useProductsCrud";
import useProductsList from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useProductsList";

export type ProductsFiltersForm = {
    searchInput: string;
    client: ClientSchema | null;
    page: number;
};

type ProductsContextState = {
    productsFiltersForm: UseFormReturnType<ProductsFiltersForm>;
    refetch: () => void;
    products: ProductSchema[];
    productsCrud: ProductsCrud;
    paginationInfo?: PaginationInfoSchema;
};

const useProductsContextState = (): ProductsContextState => {
    const productsFiltersForm = useForm<ProductsFiltersForm>({
        initialValues: {
            searchInput: "",
            client: null,
            page: 1,
        },
    });

    const [debouncedSearchInput] = useDebouncedValue(
        productsFiltersForm.values.searchInput,
        500
    );

    const { products, paginationInfo, queryKey, refetch } = useProductsList({
        clientId: productsFiltersForm.values.client?.id,
        searchInput: debouncedSearchInput,
        page: productsFiltersForm.values.page,
        itemsPerPage: 10,
    });
    const productsCrud = useProductsCrud({ queryKey });

    return {
        productsFiltersForm,
        refetch,
        products,
        productsCrud,
        paginationInfo,
    };
};

export const [ProductsContextProvider, useProductsContext] =
    makeContext<ProductsContextState>(useProductsContextState, "Products");
