import { NumberOutlined } from "@ant-design/icons";
import { Button, Form, InputNumber, Popover } from "antd";

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

import { FormServiceFieldHandlingCodeOnPageLoad } from "./codeOnPageLoad.js";
import { FormServiceFieldHandlingCodeOptOut } from "./codeOpOut.js";
import { FormServiceFieldHandlingCodeOptIn } from "./codeOptIn.js";
import { FormServiceFieldHandlingDynamicField } from "./dynamicField.js";
import { FormServiceFieldHandlingGoogleConsentMode } from "./googleConsentMode.js";
import { FormServiceFieldHandlingTagManagerEventName } from "./tagManagerEventName.js";
import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { Notices } from "../../../../common/notices.js";
import { FormHeadline } from "../../../headline.js";
import { FormServiceLayout } from "../../../layout.js";

import type { FormServiceValueProps } from "../../../../../types/formService.js";
import type { NoticeEntry } from "../../../../common/notices.js";
import type { FC } from "react";

const FormServiceFieldHandlingCompose: FC = () => {
    const { __, _i } = useI18n();
    const { template, setCookiesViaManager, contentBlockerTemplates, defaultTemplateValues, isGcm } = useFormService();

    const templateDefaultName = defaultTemplateValues?.name || "";
    const { managerLabel } = getManagerDependingVariables(setCookiesViaManager, {
        isGcm,
        presetId: template?.identifier,
    });
    const scanResult = template?.consumerData.scan;
    const technicalHandlingIntegration = template?.consumerData.technicalHandlingIntegration;

    const notices = (
        [
            {
                message: template?.technicalHandlingNotice,
                severity: "info",
            },
            {
                message:
                    technicalHandlingIntegration && template.codeOptIn
                        ? _i(
                              __(
                                  "The {{strong}}%1$s{{/strong}} plugin is connected to this service. This means that the scripts mentioned below may not be run exactly as they are or may be changed. So, it's best not to make any further changes or delete the script. Instead, if you want to make changes related to {{strong}}%2$s{{/strong}}, please do it directly in the {{strong}}%1$s{{/strong}}.",
                                  technicalHandlingIntegration.name,
                                  template.name,
                              ),
                              { strong: <strong /> },
                          )
                        : undefined,
                severity: "info",
            },
            !!scanResult &&
                template.codeOptIn &&
                !technicalHandlingIntegration &&
                // https://regex101.com/r/v1zIhQ/1
                !/^(wordpress-comments|matomo-plugin.*)$/.test(template.identifier) && {
                    message:
                        contentBlockerTemplates.length > 0
                            ? __(
                                  'You are currently embedding "%1$s" outside of Real Cookie Banner. You can have it blocked via a content blocker before consenting. Alternatively, you can use the following opt-in script to load %1$s directly into Real Cookie Banner.<br /><br />If you want to embed "%1$s" via Real Cookie Banner, you have to deactivate the content blocker at the end of the form and remove "%1$s" outside Real Cookie Banner.<br /><br />If you prefer to keep the current integration, you only have to delete the opt-in script in this form.',
                                  templateDefaultName,
                              )
                            : __(
                                  "If you have already used %s before creating this service, please deactivate the script/plugin with which the service was loaded so far. The opt-in script will now take care of the correct integration.",
                                  templateDefaultName,
                              ),
                    severity: "warning",
                },
        ] as NoticeEntry[]
    )
        .filter(Boolean)
        .filter(({ message }) => message);

    return (
        <>
            <FormHeadline
                offset={FormServiceLayout.labelCol.span}
                headlineExtra={
                    <Popover
                        title={__("Priority of script execution")}
                        placement="bottomRight"
                        overlayStyle={{ maxWidth: 500 }}
                        forceRender
                        content={
                            <Form.Item<FormServiceValueProps>
                                name="executePriority"
                                rules={[
                                    {
                                        type: "number",
                                        min: 0,
                                        max: 99,
                                        required: true,
                                        message: __("Please provide a valid priority!"),
                                    },
                                ]}
                                style={{ marginBottom: 0 }}
                                extra={
                                    <p className="description" style={{ margin: "10px 0 0 0" }}>
                                        {_i(
                                            __(
                                                "Scripts executed on opt-in or on opt-out can have the property {{code}}unique-write-name{{/code}}. If multiple scripts have the same name, only one will be executed to avoid multiple executions. If scripts with the same name are executed in different services, the one with the lowest priority is executed (defines the execution order). Changing the priority is relevant, for example, if you create two services for tracking with and without cookies (on different legal bases) for the same analysis tool.",
                                            ),
                                            { code: <code /> },
                                        )}
                                    </p>
                                }
                            >
                                <InputNumber min={0} max={99} addonBefore={__("Priority")} />
                            </Form.Item>
                        }
                    >
                        <Button type="link" icon={<NumberOutlined />}>
                            {__("Priority")}
                        </Button>
                    </Popover>
                }
                description={
                    !managerLabel
                        ? __(
                              "Define HTML and JavaScript code that is executed when a visitor decides to accept or reject this service or when a page is loaded. It is important to define the executed code correctly, as this ensures that scripts are executed and cookies are set only after the user's consent.",
                          )
                        : __(
                              "Define the %1$s event that should be thrown in the data layer when a visitor decides to accept or reject this service. The event can be used as a trigger in %1$s. For users who do not allow to use %1$s a fallback can be defined. You can define HTML and JavaScript code that is executed when a visitor decides to accept or reject this service, or when a page is loaded. It is important to define the event names and executed code correctly, as this will ensure that scripts are executed and cookies are only set with the user's consent.",
                              managerLabel,
                          )
                }
            >
                {__("Technical handling")}
            </FormHeadline>
            <FormServiceFieldHandlingTagManagerEventName />
            <FormServiceFieldHandlingGoogleConsentMode />
            <FormServiceFieldHandlingDynamicField />
            {notices.length > 0 && (
                <Form.Item
                    wrapperCol={{ offset: FormServiceLayout.labelCol.span, span: FormServiceLayout.wrapperCol.span }}
                    style={{ marginBottom: 10 }}
                >
                    <Notices notices={notices} />
                </Form.Item>
            )}
            <FormServiceFieldHandlingCodeOptIn />
            <FormServiceFieldHandlingCodeOptOut />
            <FormServiceFieldHandlingCodeOnPageLoad />
        </>
    );
};

export { FormServiceFieldHandlingCompose };
