import { Form } from "antd";
import { useMemo } from "react";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { Notices } from "../../../../common/notices.js";

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

const FormServiceFieldHandlingSkipIfActiveNotice: FC<{ name: keyof FormServiceValueProps }> = ({ name }) => {
    const { __, _i } = useI18n();
    const { skipIfActiveComponents } = useFormService();
    const componentKeys = useMemo(() => Object.keys(skipIfActiveComponents), [skipIfActiveComponents]);

    return (
        <Form.Item noStyle shouldUpdate={(prevValues, nextValues) => prevValues[name] !== nextValues[name]}>
            {({ getFieldValue }) => {
                const value = getFieldValue(name) as string;

                // Find `skip-if-active` and their active components
                const matches = ([...value.matchAll(/\s+(skip-if-active=")([^"]+)(")/gm)] as [...string[]][])
                    .map(([, , components]) =>
                        components.split(",").filter((plugin) => componentKeys.indexOf(plugin) > -1),
                    )
                    .flat();
                const uniq = matches.filter((plugin, i) => matches.indexOf(plugin) === i);

                if (uniq.length === 0) {
                    return null;
                }

                return (
                    <div style={{ marginTop: 10 }}>
                        <Notices
                            notices={[
                                {
                                    message: _i(
                                        __(
                                            "The code above contains HTML tags that are skipped when one of the following plugins is active: {{strong/}}. {{i}}What does this mean for me?{{/i}} In most cases, another plugin will take over the execution of the technical code, and you have to create a corresponding content blocker.",
                                        ),
                                        {
                                            strong: (
                                                <strong>
                                                    {uniq.map((plugin) => skipIfActiveComponents[plugin]).join(", ")}
                                                </strong>
                                            ),
                                            i: <i />,
                                        },
                                    ),
                                    severity: "info",
                                },
                            ]}
                        />
                    </div>
                );
            }}
        </Form.Item>
    );
};

export { FormServiceFieldHandlingSkipIfActiveNotice };
