"use client";

import { useEffect } from "react";
import { redirect } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import useAttributesActions, {
    AttributesActions,
} from "@/app/module-editor/[moduleId]/hooks/useAttributesActions";
import useAttributesList from "@/app/module-editor/[moduleId]/hooks/useAttributesList";
import useModulesActions, {
    ModulesActions,
} from "@/app/module-editor/[moduleId]/hooks/useModulesActions";
import { AttributeSchema, ModuleWithAttributesSchema } from "@/lib/client";
import { getModuleWithAttributesOptions } from "@/lib/client/@tanstack/react-query.gen";
import makeContext from "@/lib/contextFactory/contextFactory";

type ModuleEditorContextState = {
    module?: ModuleWithAttributesSchema;
    refetchModule: () => void;
    attributes: AttributeSchema[];
    refetchAttributes: () => void;
    attributeActions: AttributesActions;
    moduleActions: ModulesActions;
};

type Props = {
    moduleId: number;
};

const useModuleEditorContextState = ({
    moduleId,
}: Props): ModuleEditorContextState => {
    const { data, refetch: refetchModule } = useQuery(
        getModuleWithAttributesOptions({ path: { pk: moduleId } })
    );
    const module = data?.entity;

    const { attributes, refetch: refetchAttributes } = useAttributesList();

    useEffect(() => {
        if (module?.isBuiltIn) {
            redirect("modules");
        }
    }, [module]);

    const attributeActions = useAttributesActions({
        module,
        refetchModule,
        refetchAttributes,
    });

    const moduleActions = useModulesActions({
        module,
        refetchModule,
    });

    return {
        module,
        refetchModule,
        attributes,
        refetchAttributes,
        attributeActions,
        moduleActions,
    };
};

export const [ModuleEditorContextProvider, useModuleEditorContext] =
    makeContext<ModuleEditorContextState, Props>(
        useModuleEditorContextState,
        "ModuleEditor"
    );
