import { useCallback } from "react";

import type { ServiceTagManager } from "@devowl-wp/cookie-consent-web-client";

import { useFormHandler } from "./useFormHandler.js";
import { useNavLinksPageTypes } from "./useNavLinksPageTypes.js";
import { useI18n } from "../contexts/i18n.js";

import type { FormSettingsValueProps } from "../types/formSettings.js";

type UseFormHandler = typeof useFormHandler<FormSettingsValueProps, object>;

function useFormSettingsHandler(
    opts: Pick<FormSettingsValueProps, "isCountryBypass" | "isTcf" | "isGcm"> &
        Omit<Parameters<UseFormHandler>[0], "defaultValues" | "i18n" | "isEdit" | "entityTemplateVersion" | "template">,
) {
    const { __ } = useI18n();
    const { isTcf, isGcm, isCountryBypass } = opts;
    const availablePageTypes = useNavLinksPageTypes();

    const defaultValues: FormSettingsValueProps = {
        // General tab
        isBannerActive: false,
        isBlockerActive: false,
        operatorContactAddress: "",
        operatorContactEmail: "",
        operatorContactFormId: 0,
        operatorContactPhone: "",
        cookiePolicyId: 0,
        territorialLegalBasis: ["gdpr-eprivacy"],
        hidePageIds: [],
        navLinks: [],
        setCookiesViaManager: "none",

        // Consent tab
        isAcceptAllForBots: true,
        isRespectDoNotTrack: false,
        cookieDuration: 365,
        isDataProcessingInUnsafeCountries: false,
        isAgeNotice: true,
        isBannerLessConsent: false,
        bannerLessConsentShowOnPageIds: [],
        ageNoticeAgeLimit: "INHERIT",
        isListServicesNotice: true,
        failedConsentDocumentationHandling: "essentials",
        isSaveIp: false,
        consentDuration: 120,

        // Country Bypass tab
        isCountryBypass,
        // Automatically check boxes if already active
        countryBypassCheckboxTerms: !!isCountryBypass,
        countryBypassCheckboxAccuracy: !!isCountryBypass,
        countryBypassCountries: [],
        countryBypassType: "all",

        // TCF tab
        isTcf,
        operatorCountry: "",
        tcfCheckboxTerms: !!isTcf,
        tcfCheckboxVisually: !!isTcf,

        // Google Consent Mode tab
        isGcm,
        isGcmShowRecommandationsWithoutConsent: false,
        isGcmCollectAdditionalDataViaUrlParameters: false,
        isGcmRedactAdsDataWithoutConsent: true,
        isGcmListPurposes: true,

        // Multisite tabe
        isConsentForwarding: false,
        forwardTo: [],
        crossDomains: "",

        // Affiliate tab
        affiliateLink: "",
        affiliateLabelBehind: "",
        affiliateLabelDescription: "",
    };

    const handlers = useFormHandler<FormSettingsValueProps, object>({
        ...opts,
        defaultValues,
        i18n: {
            successMessage: __("Successfully updated settings!"),
            validationError: __("The settings could not be saved due to missing/invalid form values."),
            unloadConfirm: __("You have unsaved changes. If you leave this page, your changes will be discarded."),
        },
    });

    const { form } = handlers;

    let lastSetCookiesViaManager: ServiceTagManager;
    const onValuesChange = useCallback(
        (changedValues: FormSettingsValueProps, values: FormSettingsValueProps) => {
            handlers.onValuesChange(changedValues, values);

            const { navLinks, isGcm } = changedValues;

            if (navLinks?.length > 0) {
                for (const navLinkIdx in navLinks) {
                    const navLink = navLinks[navLinkIdx];
                    if (navLink?.pageType && navLink.pageType !== "other" && !Object.hasOwn(navLink, "label")) {
                        setTimeout(
                            () =>
                                handlers.form.setFieldValue(
                                    ["navLinks", +navLinkIdx, "label"],
                                    availablePageTypes.find(({ name }) => name === navLinks[navLinkIdx].pageType).label,
                                ),
                            50,
                        );
                    }
                }
            }

            if (isGcm === false) {
                lastSetCookiesViaManager = form.getFieldValue("setCookiesViaManager");
                setTimeout(() => {
                    handlers.form.setFieldsValue({ setCookiesViaManager: "none" });
                }, 50);
            }

            if (isGcm === true && lastSetCookiesViaManager === "googleTagManagerWithGcm") {
                lastSetCookiesViaManager = undefined;
                setTimeout(() => {
                    handlers.form.setFieldsValue({ setCookiesViaManager: "googleTagManagerWithGcm" });
                }, 50);
            }
        },
        [handlers.onValuesChange, handlers.form],
    );

    // Overwrite onFinish to handle term checkboxes
    const onFinish = useCallback(
        async (values: FormSettingsValueProps) => {
            handlers.onFinish(values);

            // When TCF compatibility gets deactivated, the user needs to recheck the policies and terms
            if (!values.isTcf) {
                form.setFieldsValue({
                    tcfCheckboxTerms: false,
                    tcfCheckboxVisually: false,
                });
            }

            // When Country Bypass compatibility gets deactivated, the user needs to recheck the policies and terms
            if (!values.isCountryBypass) {
                form.setFieldsValue({
                    countryBypassCheckboxTerms: false,
                    countryBypassCheckboxAccuracy: false,
                });
            }
        },
        [handlers.onFinish, form],
    );

    return {
        ...handlers,
        onFinish,
        onValuesChange,
        defaultValues,
        contextValue: {
            isCountryBypass,
            isTcf,
            isGcm,
        },
    };
}

export { useFormSettingsHandler };
