import { QuestionCircleFilled } from "@ant-design/icons";
import { App, Checkbox, Col, Form, Row, Tooltip } from "antd";
import { useMemo, useState } from "react";

import { EServiceTemplateGoogleConsentModeTypes } from "@devowl-wp/api-real-cookie-banner";
import { getManagerDependingVariables } from "@devowl-wp/cookie-consent-web-client";
import { copyToClipboard, slugify } from "@devowl-wp/react-utils";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { FormValueDifferFromTemplateTag, diffByJsonStringify } from "../../../valueDifferFromTemplateTag.js";

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

const FormServiceFieldHandlingGoogleConsentMode: FC = () => {
    const { __, _i } = useI18n();
    const { isGcm, setCookiesViaManager, template } = useFormService();
    const [ref, setRef] = useState<HTMLDivElement>();
    const { message } = App.useApp();
    const { useManager, serviceIsManager } = getManagerDependingVariables(setCookiesViaManager, {
        isGcm,
        presetId: template?.identifier,
    });

    const googleContentModeTranslations = useMemo(
        () => ({
            [EServiceTemplateGoogleConsentModeTypes.AdStorage]: __(
                "Storing and reading of data such as cookies (web) or device identifiers (apps) related to advertising.",
            ),
            [EServiceTemplateGoogleConsentModeTypes.AdUserData]: __(
                "Sending user data to Google for online advertising purposes.",
            ),
            [EServiceTemplateGoogleConsentModeTypes.AdPersonalization]: __(
                "Evaluation and display of personalized advertising.",
            ),
            [EServiceTemplateGoogleConsentModeTypes.AnalyticsStorage]: __(
                "Storing and reading of data such as cookies (web) or device identifiers (apps), related to analytics (e.g. visit duration).",
            ),
            [EServiceTemplateGoogleConsentModeTypes.FunctionalityStorage]: __(
                "Storing and reading of data that supports the functionality of the website or app (e.g. language settings).",
            ),
            [EServiceTemplateGoogleConsentModeTypes.PersonalizationStorage]: __(
                "Storing and reading of data related to personalization (e.g. video recommendations).",
            ),
            [EServiceTemplateGoogleConsentModeTypes.SecurityStorage]: __(
                "Storing and reading of data related to security (e.g. authentication functionality, fraud prevention, and other user protection).",
            ),
        }),
        [],
    );

    const uniqueNameAdditionalConsentTypeComponent = useManager === "googleTagManagerWithGcm" && (
        <Col span={24}>
            <Form.Item<FormServiceValueProps>
                noStyle
                shouldUpdate={({ uniqueName: aUniqueName, name: aName }, { uniqueName: bUniqueName, name: bName }) =>
                    aUniqueName !== bUniqueName || aName !== bName
                }
            >
                {({ getFieldValue }) => {
                    const uniqueName = getFieldValue("uniqueName") || slugify(getFieldValue("name"));

                    return (
                        !!uniqueName && (
                            <Tooltip
                                title={__(
                                    'Accessible as "Additional Consent" in Google Tag Manager to fire tags only if consent for this service has been given.',
                                )}
                            >
                                <Checkbox checked disabled>
                                    <code
                                        onClick={() => {
                                            copyToClipboard(uniqueName);
                                            message.success(__("Successfully copied to the clipboard!"));
                                        }}
                                    >
                                        {uniqueName}
                                    </code>
                                    : {__("Unique identifier of this service")}
                                    &nbsp;
                                    <QuestionCircleFilled />
                                </Checkbox>
                            </Tooltip>
                        )
                    );
                }}
            </Form.Item>
        </Col>
    );

    return (
        isGcm &&
        !serviceIsManager && (
            <Form.Item<FormServiceValueProps> label={__("Requested consent types for Google Consent Mode")}>
                <Row>
                    {uniqueNameAdditionalConsentTypeComponent}
                    <Form.Item<FormServiceValueProps> noStyle name="googleConsentModeConsentTypes">
                        <Checkbox.Group style={{ marginTop: 6 }}>
                            {Object.values(EServiceTemplateGoogleConsentModeTypes).map((val) => (
                                <Col key={val} span={24}>
                                    <Checkbox value={val}>
                                        <code>{val}</code>: {googleContentModeTranslations[val]}
                                    </Checkbox>
                                </Col>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                </Row>
                <p className="description" style={{ marginTop: 10 }} ref={setRef}>
                    <FormValueDifferFromTemplateTag
                        form="service"
                        valueName="googleConsentModeConsentTypes"
                        widthOfRef={ref}
                        difference={diffByJsonStringify}
                        renderDiff={(value) => (
                            <Row>
                                {uniqueNameAdditionalConsentTypeComponent}
                                <Checkbox.Group style={{ marginTop: 6 }} value={value} disabled>
                                    {Object.values(EServiceTemplateGoogleConsentModeTypes).map((val) => (
                                        <Col key={val} span={24}>
                                            <Checkbox value={val}>
                                                <code>{val}</code>: {googleContentModeTranslations[val]}
                                            </Checkbox>
                                        </Col>
                                    ))}
                                </Checkbox.Group>
                            </Row>
                        )}
                    />
                    {_i(
                        __(
                            "You must obtain consent according to the Google Consent Mode based on so-called consent types, {{strong}}if the service can respect these consent types{{/strong}} (check the documentation of the provider of this service to find out if an integration has been implemented). Especially for Google services, you should request all necessary consent types in order to be able to collect as much data as possible. Consent in consent types is only granted if the website visitor explicitly agrees to all services (with all features) or explicitly agrees to these consent types in the individual privacy settings, but not if they do not exercise their right to object if you use this service on the legal basis of a legitimate interest.",
                        ),
                        { strong: <strong /> },
                    )}
                </p>
            </Form.Item>
        )
    );
};

export { FormServiceFieldHandlingGoogleConsentMode };
