import { CheckCircleFilled } from "@ant-design/icons";
import {
    Alert,
    Card,
    Checkbox,
    Col,
    Collapse,
    Form,
    Input,
    Popconfirm,
    Radio,
    Row,
    Select,
    Space,
    Tooltip,
} from "antd";
import { useMemo } from "react";

import { joinWithAndSeparator } from "@devowl-wp/react-cookie-banner";
import { jsxJoin, parents } from "@devowl-wp/react-utils";

import { useCreateCookiePolicyPageButton } from "./general.js";
import { useFormSettings } from "../../../contexts/formSettings.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useUpsell } from "../../../contexts/upsell.js";
import { useTerritorialLegalBasisArticles } from "../../../hooks/useTerritorialLegalBasisArticles.js";
import { LearnMoreTag } from "../../common/learnMoreTag.js";
import { UpsellTag } from "../../upsell/tag.js";

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

const { Panel } = Collapse;

const FormSettingsConsentTabContent: FC = () => {
    const { __, _i, _n } = useI18n();
    const { isPro } = useUpsell();
    const {
        isTcf,
        consentsDeletedAt,
        iso3166OneAlpha2,
        ageNotice,
        ageNoticeCountryAgeMap,
        predefinedDataProcessingInSafeCountriesLists,
        onCustomizeClick,
        bannerlessConsentChecks,
        renderPageSelector: RenderPageSelector,
    } = useFormSettings();

    const calculateTerritorialLegalBasisArticles = useTerritorialLegalBasisArticles({
        predefinedDataProcessingInSafeCountriesLists,
        iso3166OneAlpha2,
    });
    const handleCreateCookiePolicy = useCreateCookiePolicyPageButton();

    const servicesWithoutVisualContentBlocker = useMemo(
        () => bannerlessConsentChecks["legalBasisConsentWithoutVisualContentBlocker"].map(({ name }) => name),
        [bannerlessConsentChecks],
    );

    const showAgeNoticeAgeLimitDropdown = ageNotice ? ageNotice.indexOf("{{minAge}}") > -1 : true;

    return (
        <>
            <Form.Item<FormSettingsValueProps>
                noStyle
                shouldUpdate={(prevValues, curValues) =>
                    JSON.stringify(prevValues.territorialLegalBasis) !== JSON.stringify(curValues.territorialLegalBasis)
                }
            >
                {({ getFieldValue }) => {
                    const territorialLegalBasis = getFieldValue(
                        "territorialLegalBasis",
                    ) as FormSettingsValueProps["territorialLegalBasis"];
                    const {
                        legalBasis,
                        labelGdpr,
                        labelGdprEuEea,
                        safeCountriesList,
                        adequacyCountriesLists,
                        dataProcessingInUnsafeCountriesArticles,
                        dataProcessingInUnsafeCountriesArticlesLinks,
                    } = calculateTerritorialLegalBasisArticles(territorialLegalBasis);

                    return (
                        <Form.Item label={__("Consent for data processing in unsafe third countries")}>
                            <Form.Item name="isDataProcessingInUnsafeCountries" noStyle>
                                <Radio.Group>
                                    <Radio.Button disabled={!isPro} value={true}>
                                        {__("Enabled")}
                                    </Radio.Button>
                                    <Radio.Button disabled={!isPro} value={false}>
                                        {__("Disabled")}
                                    </Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            <div style={{ margin: "5px 0px 0px" }}>
                                <UpsellTag
                                    title={__("Do you need consent for data processing in unsafe countries?")}
                                    testDrive
                                    feature="data-processing-in-unsafe-countries"
                                    assetName={__("pro-modal/data-processing-in-insecure-third-countries.png")}
                                    description={_i(
                                        __(
                                            "The GDPR offers a great level of data protection. For data processing in countries where the GDPR does not apply, safety mechanisms are required that guarantee an appropriate level of protection. This is usually an adequacy decision or standard contractual clauses. If none of the safety mechanisms are in place, you must inform your website visitors about special risks and their consequences and obtain special consent in accordance with {{aGdpr}}Art. 49 GDPR{{/aGdpr}}.",
                                        ),
                                        {
                                            aGdpr: (
                                                <a
                                                    href={__("https://gdpr-text.com/read/article-49/")}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                />
                                            ),
                                        },
                                    )}
                                />
                            </div>
                            <p className="description">
                                {_i(
                                    __(
                                        `Countries in which {{legalBasis/}} are not applicable are considered as unsafe third countries in which no personal data of your visitors may initially be transmitted or processed. For some countries, there is an {{adequacy}}{{u}}adequacy decision{{/u}}{{/adequacy}} that declares the country to be safe. You can also conclude {{aSCC}}standard contractual clauses{{/aSCC}} with service providers that contractually guarantee safe data processing. Sometimes, however, none of these safety mechanisms exist and it is not possible to waive the use of the service. In accordance with {{article/}}, it is possible to obtain the consent of website visitors for the one-off and multiple processing of personal data. Consent to the regular processing of data in unsafe third countries in this way is controversial. This means that at least some of the convenient services can still be used. Activate this option to flag the processing of personal data in unsafe countries and obtain the special consent from your visitors.`,
                                    ),
                                    {
                                        legalBasis: jsxJoin(
                                            legalBasis.map((s) => {
                                                const tooltip =
                                                    [labelGdpr, labelGdprEuEea].indexOf(s) > -1
                                                        ? safeCountriesList["GDPR"]
                                                        : "";
                                                return tooltip ? (
                                                    <Tooltip key={s} title={tooltip}>
                                                        <u style={{ textDecorationStyle: "dashed" }}>{s}</u>
                                                    </Tooltip>
                                                ) : (
                                                    <span key={s}>{s}</span>
                                                );
                                            }),
                                            __(" or "),
                                        ),
                                        article: jsxJoin(
                                            dataProcessingInUnsafeCountriesArticles.map((article, i) => {
                                                return (
                                                    <a
                                                        key={article}
                                                        href={dataProcessingInUnsafeCountriesArticlesLinks[i]}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    >
                                                        {article}
                                                    </a>
                                                );
                                            }),
                                            __(" or "),
                                        ),
                                        u: <u style={{ textDecorationStyle: "dashed" }} />,
                                        adequacy: (
                                            <Tooltip
                                                title={jsxJoin(
                                                    adequacyCountriesLists.map((s) => <div key={s}>{s}</div>),
                                                    <br />,
                                                )}
                                            />
                                        ),
                                        aSCC: (
                                            <a
                                                href={__(
                                                    "https://commission.europa.eu/law/law-topic/data-protection/international-dimension-data-protection/standard-contractual-clauses-scc_en",
                                                )}
                                                target="_blank"
                                                rel="noreferrer"
                                            />
                                        ),
                                    },
                                )}
                                &nbsp;&bull;&nbsp;
                                <a
                                    onClick={() =>
                                        onCustomizeClick("rcb-banner-texts-data-processing-in-unsafe-countries")
                                    }
                                >
                                    {__("Change text in customizer")}
                                </a>
                            </p>
                        </Form.Item>
                    );
                }}
            </Form.Item>
            <Form.Item label={__("Age notice for consent")}>
                <Form.Item name="isAgeNotice" noStyle>
                    <Radio.Group>
                        <Radio.Button value={true}>{__("Enabled")}</Radio.Button>
                        <Radio.Button value={false}>{__("Disabled")}</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                <p className="description">
                    {_i(
                        __(
                            `In accordance with {{a}}Art. 8 GDPR{{/a}}, consent to services that process personal data and/or set cookies can only be given from the age of 16 years (varying in some EU countries) or together with a legal guardian. If your website does not clearly and exclusively address adults (e.g. dating or porn sites), you as the website operator must inform children under the minimum age in simple language that they are not allowed to consent to non-essential services without their legal guardian.`,
                        ),
                        {
                            a: (
                                <a
                                    href={__("https://gdpr-text.com/read/article-8/")}
                                    target="_blank"
                                    rel="noreferrer"
                                />
                            ),
                        },
                    )}
                    &nbsp;&bull;&nbsp;
                    <a onClick={() => onCustomizeClick("rcb-banner-texts-age-notice")}>
                        {__("Change text in customizer")}
                    </a>
                </p>
                <Form.Item<FormSettingsValueProps>
                    noStyle
                    shouldUpdate={(
                        {
                            isAgeNotice: isAgeNoticeA,
                            operatorCountry: operatorCountryA,
                            ageNoticeAgeLimit: ageNoticeAgeLimitA,
                        },
                        {
                            isAgeNotice: isAgeNoticeB,
                            operatorCountry: operatorCountryB,
                            ageNoticeAgeLimit: ageNoticeAgeLimitB,
                        },
                    ) =>
                        isAgeNoticeA !== isAgeNoticeB ||
                        operatorCountryA !== operatorCountryB ||
                        ageNoticeAgeLimitA !== ageNoticeAgeLimitB
                    }
                >
                    {({ getFieldValue }) => (
                        <>
                            <Space.Compact
                                className="rcb-antd-select-addon"
                                style={{
                                    display:
                                        getFieldValue("isAgeNotice") && showAgeNoticeAgeLimitDropdown
                                            ? undefined
                                            : "none",
                                }}
                            >
                                <Input addonBefore={__("Age limit")} />
                                <Form.Item noStyle name="ageNoticeAgeLimit">
                                    <Select showSearch optionFilterProp="children">
                                        {Object.keys(ageNoticeCountryAgeMap).map((key) => {
                                            const operatorCountry = getFieldValue("operatorCountry");
                                            const useAgeKey =
                                                key === "INHERIT"
                                                    ? operatorCountry && ageNoticeCountryAgeMap[operatorCountry]
                                                        ? operatorCountry
                                                        : "GDPR"
                                                    : key;

                                            return (
                                                <Select.Option key={key} value={key}>
                                                    <Row>
                                                        <Col flex="auto">
                                                            {key === "INHERIT"
                                                                ? __(
                                                                      "Determine age limit based on specified website operator country",
                                                                  )
                                                                : key === "GDPR"
                                                                  ? __("GDPR standard")
                                                                  : iso3166OneAlpha2[key]}
                                                        </Col>
                                                        <Col flex="none">
                                                            {__("%d years", ageNoticeCountryAgeMap[useAgeKey])}
                                                        </Col>
                                                    </Row>
                                                </Select.Option>
                                            );
                                        })}
                                    </Select>
                                </Form.Item>
                            </Space.Compact>
                            {getFieldValue("isAgeNotice") &&
                                showAgeNoticeAgeLimitDropdown &&
                                ["INHERIT", "GDPR"].indexOf(getFieldValue("ageNoticeAgeLimit")) === -1 && (
                                    <div
                                        className="notice notice-info inline below-h2 notice-alt"
                                        style={{ margin: "10px 0 0" }}
                                    >
                                        <p>
                                            {_i(
                                                __(
                                                    "The age limit should only differ from the age limit in the country of the website operator if you are primarily targeting visitors from another country with a {{strong}}higher{{/strong}} age limit. Changing the age limit therefore only makes sense in a few exceptional cases.",
                                                ),
                                                {
                                                    strong: <strong />,
                                                },
                                            )}
                                        </p>
                                    </div>
                                )}
                        </>
                    )}
                </Form.Item>
            </Form.Item>
            <Form.Item label={__("Naming of all services in first view")}>
                <Form.Item name="isListServicesNotice" noStyle>
                    <Radio.Group>
                        <Radio.Button value={true}>{__("Enabled")}</Radio.Button>
                        <Radio.Button value={false}>{__("Disabled")}</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                <p className="description">
                    {__(
                        "The visitor to your website should be adequately informed of what he or she is agreeing to when consenting to all services. Therefore, in the first view of the cookie banner, all services can be written out by name in a comma-separated list. Your website visitor can thus better assess whether he really wants to agree to all services without visiting the individual privacy settings.",
                    )}
                    &nbsp;&bull;&nbsp;
                    <a onClick={() => onCustomizeClick("rcb-banner-texts-list-services-notice")}>
                        {__("Change text in customizer")}
                    </a>
                </p>
            </Form.Item>
            <Form.Item<FormSettingsValueProps>
                noStyle
                shouldUpdate={(prevValues, nextValues) =>
                    prevValues.isBannerLessConsent !== nextValues.isBannerLessConsent ||
                    prevValues.cookiePolicyId !== nextValues.cookiePolicyId ||
                    prevValues.isTcf !== nextValues.isTcf
                }
            >
                {({ getFieldValue, setFieldsValue }) => {
                    const isBannerLessConsent = getFieldValue(
                        "isBannerLessConsent",
                    ) as FormSettingsValueProps["isBannerLessConsent"];
                    const cookiePolicyId = getFieldValue("cookiePolicyId") as FormSettingsValueProps["cookiePolicyId"];
                    const isTcf = getFieldValue("isTcf") as FormSettingsValueProps["isTcf"];

                    return (
                        <Form.Item<FormSettingsValueProps> label={__("Banner-less consent")}>
                            <Form.Item<FormSettingsValueProps> name="isBannerLessConsent" noStyle>
                                <Radio.Group style={{ display: isBannerLessConsent ? undefined : "none" }}>
                                    <Radio.Button disabled={!isPro} value={true}>
                                        {__("Enabled")}
                                    </Radio.Button>
                                    <Radio.Button disabled={!isPro} value={false}>
                                        {__("Disabled")}
                                    </Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            {!isBannerLessConsent && (
                                <Radio.Group value={false}>
                                    <Popconfirm
                                        title={
                                            <Space key="alerts" direction="vertical" size="small">
                                                <div>
                                                    {__(
                                                        "Enabling the option means that the cookie banner will no longer be displayed on your website. Consent to certain services can only be given via visual content blockers or the legal link to the privacy settings (only a few website visitors use this). To comply with your information obligations, especially for essential services, you must have a cookie policy on your website or provide all the necessary information manually in your privacy policy. The document must be linked on every subpage of the website.",
                                                    )}
                                                </div>
                                                <div>
                                                    {cookiePolicyId > 0 ? (
                                                        <>
                                                            <CheckCircleFilled style={{ color: "#52c41a" }} />
                                                            &nbsp;
                                                            {__("Cookie policy page already created")}
                                                        </>
                                                    ) : (
                                                        <Checkbox defaultChecked>
                                                            {__("Create cookie policy page with content automatically")}
                                                        </Checkbox>
                                                    )}
                                                </div>
                                                {servicesWithoutVisualContentBlocker.length > 0 && (
                                                    <Alert
                                                        type="warning"
                                                        message={_n(
                                                            "The service %s does not have a visual content blocker, which is why website visitors without cookie banners cannot consent to it (except via the legal link to change the privacy settings). As a result, this service will normally no longer be embeded on your website.",
                                                            "The services %s do not have visual content blockers, which is why website visitors without cookie banners cannot consent to them (except via the legal link to change the privacy settings). As a result, these services will normally no longer be embeded on your website.",
                                                            servicesWithoutVisualContentBlocker.length,
                                                            joinWithAndSeparator(
                                                                servicesWithoutVisualContentBlocker,
                                                                __(" and "),
                                                            ),
                                                        )}
                                                        showIcon
                                                    />
                                                )}
                                                {isTcf && (
                                                    <Alert
                                                        type="warning"
                                                        message={__(
                                                            "Banner-less consent will preventing visitors from consenting to TCF vendor purposes, which will result in significantly reduced advertising revenue. We advise against using the Transparency & Consent Framework together with banner-less consent!",
                                                        )}
                                                        showIcon
                                                    />
                                                )}
                                            </Space>
                                        }
                                        cancelText={__("Cancel")}
                                        okText={__("Activate now!")}
                                        overlayStyle={{ maxWidth: 750 }}
                                        onCancel={() => {
                                            setFieldsValue({ isBannerLessConsent: false });
                                        }}
                                        onConfirm={async (e) => {
                                            setFieldsValue({ isBannerLessConsent: true });

                                            const popconfirm = parents(
                                                e.target as HTMLElement,
                                                ".rcb-antd-popconfirm",
                                                1,
                                            );

                                            // Automatically create the cookie policy page
                                            if ((popconfirm[0].querySelector("input") as HTMLInputElement).checked) {
                                                await handleCreateCookiePolicy();
                                            }
                                        }}
                                        placement="bottomLeft"
                                    >
                                        <Radio.Button
                                            disabled={!isPro}
                                            value={true}
                                            onClick={(e) => e.stopPropagation()}
                                            onChange={(e) => e.stopPropagation()}
                                        >
                                            {__("Enabled")}
                                        </Radio.Button>
                                    </Popconfirm>
                                    <Radio.Button disabled={!isPro} value={false}>
                                        {__("Disabled")}
                                    </Radio.Button>
                                </Radio.Group>
                            )}
                            <div style={{ margin: "5px 0px 0px", display: isPro ? "none" : undefined }}>
                                <UpsellTag
                                    title={__("Do you want to avoid using a cookie banner?")}
                                    testDrive
                                    feature="banner-less-consent"
                                    assetName={__("pro-modal/banner-less-consent.png")}
                                    description={__(
                                        "Bannerless consent ensures a seamless, distraction-free experience for your visitors. By using essential services and visual content blockers, you can avoid intrusive cookie banners and at the same time allow users to easily manage their consent for specific content such as YouTube videos in accordance with the legal regulations.",
                                    )}
                                />
                            </div>
                            <p className="description" style={{ marginTop: 5 }}>
                                {__(
                                    "If you only use essential services and those with a visual content blocker, you can avoid using a cookie banner so that your website visitors are not distracted. Visual content blockers initially block all services that require consent. For example, if a visitor wants to watch a YouTube video, they can give their consent in the content blocker for these videos to always be loaded in future. To fulfill your information obligations, you should have a cookie policy on your website (created automatically) or provide all necessary information in your privacy policy (manually).",
                                )}
                            </p>
                        </Form.Item>
                    );
                }}
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, nextValues) =>
                    prevValues.isBannerLessConsent !== nextValues.isBannerLessConsent
                }
            >
                {({ getFieldValue }) => {
                    const isBannerLessConsent = getFieldValue(
                        "isBannerLessConsent",
                    ) as FormSettingsValueProps["isBannerLessConsent"];
                    return (
                        isBannerLessConsent &&
                        isPro && (
                            <Form.Item label={__("Show cookie banner on specific pages")}>
                                <Form.Item name="bannerLessConsentShowOnPageIds" noStyle>
                                    <RenderPageSelector
                                        id="bannerLessConsentShowOnPageIds"
                                        disabled={false}
                                        multiple={true}
                                        onlyPages={false}
                                    />
                                </Form.Item>
                                <p className="description">
                                    {__(
                                        "The cookie banner is generally not displayed due to consent being obtained without a banner (banner-less). However, if non-essential services without visual content blockers are required on certain subpages, you can display the cookie banner when the visitor accesses one of these subpages for the first time. This is useful e.g. for using services like Google Ads Conversion Tracking or Google Analytics on specific landing pages.",
                                    )}
                                </p>
                            </Form.Item>
                        )
                    );
                }}
            </Form.Item>
            <Form.Item label={__("Handling of failed consent documentation")} style={{ marginBottom: 0 }}>
                <Form.Item name="failedConsentDocumentationHandling" noStyle>
                    <Radio.Group>
                        <Radio.Button value="essentials">{__("Allow only essential services")}</Radio.Button>
                        <Radio.Button value="optimistic">{__("Respect user consent")}</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                <p className="description">
                    {__(
                        "It is possible that your website can still be accessed (e.g. due to a highly scalable page cache), but that consents given in the cookie banner can no longer be documented (e.g. server overload due to too much traffic). In this case, Real Cookie Banner will try to document the consent as soon as the server is avaible again in accordance with your legal obligations. In the meantime, there is a risk if the consent of your website visitor is respected and thus non-essential services are played out whose consent or legitimate interest you cannot prove. However, if you expect a temporary overload of your server, e.g. due to an event, it may be economically advantageous to take this risk.",
                    )}
                </p>
            </Form.Item>
            <Collapse ghost>
                <Panel
                    key="nav"
                    header={
                        <a>
                            {__(
                                "Advanced settings (Do not track, behavior for bots, saving of IP addresses, duration of cookie consent, lifetime of consent documentations)",
                            )}
                        </a>
                    }
                >
                    <Card style={{ margin: 5 }}>
                        <Form.Item label={__('Respect "Do Not Track"')}>
                            <Form.Item name="isRespectDoNotTrack" noStyle>
                                <Radio.Group>
                                    <Radio.Button value={true}>{__("Enabled")}</Radio.Button>
                                    <Radio.Button value={false}>{__("Disabled")}</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            <div style={{ margin: "5px 0px 0px" }}>
                                <LearnMoreTag url={__("https://devowl.io/data-protection/do-not-track/")} />
                            </div>
                            <p className="description">
                                {__(
                                    `Users can set the "Do not track" HTTP header in their browser to indicate that they do not want to be tracked. If you enable this option, users will be able to access your website with this HTTP header without a cookie banner, if there are no non-essential services that are used based on legitimate interest. Only the non-rejectable services will be used in the case.`,
                                )}
                                &nbsp;
                                {isTcf && (
                                    <strong>
                                        {__(
                                            "According to the TCF standard, all rights of objection are also exercised for these visitors, as the cookie banner is not displayed at all and thus no transparency about legitimate interest can be established.",
                                        )}
                                    </strong>
                                )}
                            </p>
                        </Form.Item>
                        <Form.Item label={__("Automatically accept all services for bots")}>
                            <Form.Item name="isAcceptAllForBots" noStyle>
                                <Radio.Group>
                                    <Radio.Button value={true}>{__("Enabled")}</Radio.Button>
                                    <Radio.Button value={false}>{__("Disabled")}</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            <p className="description">
                                {_i(
                                    __(
                                        "Bots are not subject of the GDPR according to {{aGdpr}}Art. 1 GDPR{{/aGdpr}} and technically cannot give consent to the processing of personal data and the setting of cookies. As a result, they may consider your site as slow if a cookie banner permanently blocks all other content. Therefore, you should allow the bots to browse your site without consent, but still allow all services.",
                                    ),
                                    {
                                        aGdpr: (
                                            <a
                                                href={__("https://gdpr-text.com/read/article-1/")}
                                                target="_blank"
                                                rel="noreferrer"
                                            />
                                        ),
                                    },
                                )}
                            </p>
                        </Form.Item>
                        <Form.Item label={__("Save IP address on consent")}>
                            <Form.Item name="isSaveIp" noStyle>
                                <Radio.Group>
                                    <Radio.Button value={true}>{__("Enabled")}</Radio.Button>
                                    <Radio.Button value={false}>{__("Disabled")}</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            <p className="description">
                                {_i(
                                    __(
                                        `Depending on the country of origin, it may make legal sense to store the IP address of the user who consents. On the other hand, you must inform the user in your privacy policy that you are storing this IP address together with the consent, as this is legally {{a}}personal data{{/a}}.`,
                                    ),
                                    {
                                        a: (
                                            <a
                                                href={__("https://devowl.io/data-protection/personal-data-gdpr/")}
                                                target="_blank"
                                                rel="noreferrer"
                                            />
                                        ),
                                    },
                                )}
                            </p>
                        </Form.Item>
                        <Form.Item label={__("Duration of cookie consent")}>
                            <Form.Item
                                name="cookieDuration"
                                wrapperCol={{ span: 8 }}
                                style={{ marginBottom: 0 }}
                                rules={[
                                    {
                                        type: "number",
                                        min: 1,
                                        max: 365,
                                        transform: (v) => +v,
                                        message: __("Please use a number between %d and %d!", 1, 365),
                                    },
                                ]}
                            >
                                <Input addonAfter={__("days")} type="number" max={365} />
                            </Form.Item>
                            <p className="description">
                                {__(
                                    `The consent of a user must be limited in time. You can define how long the consent is valid. It can be valid for a maximum of 365 days because every 6-12 months you have to remind the user of the right to revoke consent (cookie banner is displayed again). If you change the behavior or content of the cookie banner meanwhile, visitors to your website will have to give their consent again, even if the time period has not yet expired.`,
                                )}
                            </p>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, nextValues) =>
                                    prevValues.cookieDuration !== nextValues.cookieDuration
                                }
                            >
                                {({ getFieldValue }) =>
                                    getFieldValue("cookieDuration") < 183 && (
                                        <div
                                            className="notice notice-warning inline below-h2 notice-alt"
                                            style={{ margin: 0 }}
                                        >
                                            <p>
                                                {__(
                                                    "You are not allowed to ask for consent again in some EU countries, such as Italy, for at least six months (unless the content of the cookie banner changes). In other countries, you must ask for consent again after 12 months at the latest. Therefore, consent should be valid for between 183 days and 365 days.",
                                                )}
                                            </p>
                                        </div>
                                    )
                                }
                            </Form.Item>
                        </Form.Item>
                        <Form.Item label={__("Delete documented consents after")}>
                            <Form.Item
                                name="consentDuration"
                                wrapperCol={{ span: 8 }}
                                style={{ marginBottom: 0 }}
                                rules={[
                                    {
                                        type: "number",
                                        min: 1,
                                        max: 120,
                                        transform: (v) => +v,
                                        message: __("Please use a number between %d and %d!", 1, 120),
                                    },
                                ]}
                            >
                                <Input addonAfter={__("months")} type="number" />
                            </Form.Item>
                            {consentsDeletedAt && (
                                <p className="description">
                                    <strong>
                                        {__(
                                            "Consents was last cleaned up on %s.",
                                            new Date(consentsDeletedAt).toLocaleString(document.documentElement.lang),
                                        )}
                                    </strong>
                                </p>
                            )}
                            <p className="description">
                                {_i(
                                    __(
                                        `Consents are automatically documented in order to be able to prove compliance with the legal requirements according to {{a}}Art. 5 GDPR{{/a}} and, in case of dispute, to prove how the consent was obtained. The absolute statute of limitations for data protection violations in most EU countries is 10 years. After that, you should delete consents in the interest of data economy.`,
                                    ),
                                    {
                                        a: (
                                            <a
                                                href={__("https://gdpr-text.com/read/article-5/")}
                                                target="_blank"
                                                rel="noreferrer"
                                            />
                                        ),
                                    },
                                )}
                            </p>
                        </Form.Item>
                    </Card>
                </Panel>
            </Collapse>
        </>
    );
};

export { FormSettingsConsentTabContent };
