import type { CommonContextProps } from "@devowl-wp/react-cookie-banner";
import type {
    FnCreateImmutableContextForSymbol,
    FnCreateImmutableContextProviderForSymbol,
    ImmutableContext,
} from "@devowl-wp/react-utils";
import { useImmutableContext, useImmutableContextProvider } from "@devowl-wp/react-utils";
import type { ClientServiceTemplate } from "@devowl-wp/service-cloud-consumer";

import type { FormServiceValueProps } from "../types/formService.js";
import type { FormSettingsValueProps } from "../types/formSettings.js";
import type { FormInstance } from "antd";

const FORM_SERVICE_CONTEXT_SYMBOL = Symbol();
type FormServiceContext = ImmutableContext<{
    initialState: Partial<
        Pick<
            FormSettingsValueProps,
            | "territorialLegalBasis"
            | "isGcm"
            | "isGcmShowRecommandationsWithoutConsent"
            | "isBannerLessConsent"
            | "isTcf"
            | "isDataProcessingInUnsafeCountries"
            | "isConsentForwarding"
            | "setCookiesViaManager"
        > & {
            form: FormInstance<FormServiceValueProps>;
            template: ClientServiceTemplate["use"];
            isEdit: boolean;
            isTemplateUpdate: boolean;
            createdTagManagers: Record<string, number[]>;
            allowLegalBasisLegalRequirement: boolean;
            templateCheck: boolean;
            skipIfActiveComponents: Record<string, string>;
            essentialGroupId: number;
            groups: Array<{
                id: number;
                name: string;
            }>;
            iso3166OneAlpha2: Record<string, string>;
            predefinedDataProcessingInSafeCountriesLists: CommonContextProps["predefinedDataProcessingInSafeCountriesLists"];
            preselectGroup: number | "preset-group-not-found";
            hasServiceByUniqueName: (slug: string) => Promise<boolean>;
            renderCodeMirror: () => JSX.Element;
            allowContentBlockerCreation: boolean;
            contentBlockerTemplates: Array<{
                identifier: string;
                name: string;
                subHeadline?: string;
            }>;
            /**
             * Allows to reset some fields depending on new values of a defined template.
             */
            defaultTemplateValues: Partial<FormServiceValueProps>;
            initiallyScrollToField: keyof FormSettingsValueProps;
        }
    >;
}>;

const useFormService: FnCreateImmutableContextForSymbol<FormServiceContext> = () =>
    useImmutableContext<FormServiceContext>(FORM_SERVICE_CONTEXT_SYMBOL);

const useFormServiceProvider: FnCreateImmutableContextProviderForSymbol<FormServiceContext> = (...args) =>
    useImmutableContextProvider<FormServiceContext>(FORM_SERVICE_CONTEXT_SYMBOL, ...args);

export { type FormServiceContext, useFormService, useFormServiceProvider };
