import { EServiceTemplateDataProcessingInCountriesSpecialTreatment } from "@devowl-wp/api-real-cookie-banner";

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

import type { FormTcfVendorContext } from "../contexts/formTcfVendor.js";
import type { FormTcfVendorTemplateValues, FormTcfVendorValueProps } from "../types/formTcfVendor.js";

type ClientTcfVendorTemplate = Record<string, never>;

type UseFormHandler = typeof useFormHandler<FormTcfVendorTemplateValues, ClientTcfVendorTemplate>;

function useFormTcfVendorHandler(
    opts: Omit<Parameters<UseFormHandler>[0], "defaultValues" | "i18n"> &
        Pick<FormTcfVendorContext["initialState"], "vendor" | "declarations">,
): ReturnType<UseFormHandler> & {
    overrideValues: (initialValues: FormTcfVendorValueProps) => FormTcfVendorValueProps;
    onFinish: (values: FormTcfVendorValueProps) => void;
    onValuesChange: (changedValues: FormTcfVendorValueProps, values: FormTcfVendorValueProps) => void;
    contextValue: Partial<FormTcfVendorContext["contextValue"]>;
} {
    const { __ } = useI18n();
    const { attributes, template, vendor, declarations, isEdit } = opts;

    const defaultValues: FormTcfVendorValueProps = {
        status: "publish",
        restrictivePurposes: { normal: {} },
        dataProcessingInCountries: [],
        dataProcessingInCountriesSpecialTreatments: [],
        templateCheck: false,
        ...(attributes || {}),
    };

    if (vendor && declarations) {
        for (const purpose of [...vendor.legIntPurposes, ...vendor.purposes].filter(Boolean)) {
            defaultValues.restrictivePurposes.normal[purpose.toString()] = {
                enabled: true,
                legInt:
                    vendor.legIntPurposes.indexOf(purpose) > -1 && vendor.specialPurposes.indexOf(purpose) === -1
                        ? "yes"
                        : "no",
            };
        }
    }

    const handlers = useFormHandler<FormTcfVendorValueProps, ClientTcfVendorTemplate>({
        ...opts,
        handleSave: async (values) => {
            // At least one purpose must be active
            const enabledPurposes =
                Object.values(values.restrictivePurposes.normal).filter(({ enabled }) => enabled).length +
                vendor.specialPurposes.length;
            if (enabledPurposes === 0) {
                throw __("You need to enable at least one purpose!");
            }

            return await opts.handleSave(values);
        },
        defaultValues,
        i18n: {
            successMessage: __("You have successfully saved the TCF vendor configuration."),
            validationError: __("The TCF vendor configuration 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."),
        },
    });

    // TCF supports also Standard Contractual clauses, so we need to force to use the SCCs and the user should not be able to uncheck it
    const overrideValues = (initialValues: FormTcfVendorValueProps) => {
        if (vendor?.additionalInformation?.transferMechanisms?.indexOf("SCCs") > -1) {
            initialValues.dataProcessingInCountriesSpecialTreatments.push(
                EServiceTemplateDataProcessingInCountriesSpecialTreatment.StandardContractualClauses,
            );
        }

        return initialValues;
    };

    return {
        ...handlers,
        defaultValues,
        overrideValues,
        contextValue: {
            isEdit,
            vendor,
            declarations,
            defaultTemplateValues: template ? defaultValues : {},
        },
    };
}

export { useFormTcfVendorHandler };
