"use client";

import { Dispatch, SetStateAction } from "react";
import useFilteredAttributes from "@/app/attributes/hooks/useFilteredAttributes";
import useAttributesActions, {
    AttributesActions,
} from "@/app/module-editor/[moduleId]/hooks/useAttributesActions";
import useAttributesList from "@/app/module-editor/[moduleId]/hooks/useAttributesList";
import { AttributeSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

type AttributesContextState = {
    attributes: AttributeSchema[];
    refetchAttributes: () => void;
    attributesActions: AttributesActions;
    search: string;
    setSearch: Dispatch<SetStateAction<string>>;
};

const useAttributesContextState = (): AttributesContextState => {
    const { attributes, refetch } = useAttributesList();
    const attributesActions = useAttributesActions({
        refetchAttributes: refetch,
    });

    const { search, setSearch, filteredAttributes } = useFilteredAttributes({
        attributes,
    });

    return {
        attributes: filteredAttributes,
        refetchAttributes: refetch,
        attributesActions,
        search,
        setSearch,
    };
};

export const [AttributesContextProvider, useAttributesContext] =
    makeContext<AttributesContextState>(useAttributesContextState, "Attribute");
