import { App, Checkbox, Form, Radio, Select, Spin } from "antd";
import { useCallback, useState } from "react";

import { jsxJoin } from "@devowl-wp/react-utils";

import { useFormSettings } from "../../../contexts/formSettings.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useUpsell } from "../../../contexts/upsell.js";
import { LearnMoreTag } from "../../common/learnMoreTag.js";
import { Notices } from "../../common/notices.js";
import { UpsellTag } from "../../upsell/tag.js";

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

const FormSettingsTcfTabContent: FC = () => {
    const { message } = App.useApp();
    const { __, _x, _i } = useI18n();
    const { isPro, isLicensed } = useUpsell();
    const {
        iso3166OneAlpha2,
        isTcf: isTcfPersisted,
        tcfAcceptedTime,
        tcfGvlDownloadTime,
        onTcfUpdateDatabase,
    } = useFormSettings();
    const [isUpdateDatabaseBusy, setUpdateDatabaseBusy] = useState(false);

    const handleUpdateGvl = useCallback(async () => {
        setUpdateDatabaseBusy(true);
        try {
            await onTcfUpdateDatabase();
            message.success(__("You successfully updated the GVL."));
        } catch (e) {
            message.error(e.responseJSON.message);
            throw e;
        } finally {
            setUpdateDatabaseBusy(false);
        }
    }, [onTcfUpdateDatabase]);

    return (
        <>
            <Form.Item label={__("Transparency & Consent Framework (TCF)")} style={{ marginBottom: 10 }}>
                <Form.Item name="isTcf" noStyle>
                    <Radio.Group>
                        <Radio.Button disabled={!isPro || !isLicensed} value={true}>
                            {__("Enabled")}
                        </Radio.Button>
                        <Radio.Button disabled={!isPro || !isLicensed} value={false}>
                            {__("Disabled")}
                        </Radio.Button>
                    </Radio.Group>
                </Form.Item>
                {isPro && !isLicensed && (
                    <div className="notice notice-error inline below-h2 notice-alt" style={{ margin: "10px 0" }}>
                        <p>
                            {__(
                                "This functionality is only available with a valid license, as the TCF Global Vendor List (GVL) must be downloaded regularly from our cloud service.",
                            )}{" "}
                            &bull;{" "}
                            <a href={`#/licensing?navigateAfterActivation=${encodeURIComponent(window.location.href)}`}>
                                {__("Activate license")}
                            </a>
                        </p>
                    </div>
                )}
                <div style={{ margin: "5px 0px 0px" }}>
                    <LearnMoreTag url={__("https://devowl.io/knowledge-base/real-cookie-banner-tcf-setup/")} />
                    <UpsellTag
                        title={__("Enable TCF compatibility?")}
                        testDrive
                        feature="tcf"
                        assetName={__("pro-modal/tcf-compatibility.png")}
                        description={__(
                            "TCF (Transparency & Consent Framework) is an industry standard for obtaining consent that is recognized in the EU. You must obtain consent in this form to fully use services such as Google Adsense and to increase your advertising revenue.",
                        )}
                    />
                </div>
                <p className="description">
                    {_i(
                        __(
                            `The {{a}}Transparency & Consent Framework (TCF){{/a}} is a standard of the European digital marketing industry association {{aIab}}IAB Europe{{/aIab}}. It allows users to consent to data collection and processing in accordance with applicable EU law and to share it with third-party services (e.g. advertising networks) in a standardized format. Some services require TCF standard consent to be used on your website. We recommend that you only enable TCF compatibility if you know you need it, as it limits the functionality of Real Cookie Banner.`,
                        ),
                        {
                            a: (
                                <a
                                    href={__("https://iabeurope.eu/transparency-consent-framework/")}
                                    target="_blank"
                                    rel="noreferrer"
                                />
                            ),
                            aIab: <a href={__("https://iabeurope.eu/")} target="_blank" rel="noreferrer" />,
                        },
                    )}
                </p>
            </Form.Item>
            <Form.Item<FormSettingsValueProps>
                noStyle
                shouldUpdate={(prevValues, curValues) =>
                    prevValues.isTcf !== curValues.isTcf ||
                    prevValues.isBannerLessConsent !== curValues.isBannerLessConsent
                }
            >
                {({ getFieldValue }) => {
                    const isTcf = getFieldValue("isTcf") as FormSettingsValueProps["isTcf"];
                    const isBannerLessConsent = getFieldValue(
                        "isBannerLessConsent",
                    ) as FormSettingsValueProps["isBannerLessConsent"];

                    return (
                        isPro &&
                        isTcf && (
                            <>
                                {tcfAcceptedTime && (
                                    <Form.Item wrapperCol={{ offset: 6 }} style={{ marginBottom: 10 }}>
                                        <p style={{ margin: 0 }}>
                                            <strong>
                                                {__(
                                                    "You last agreed to the following on %s",
                                                    new Date(tcfAcceptedTime).toLocaleString(
                                                        document.documentElement.lang,
                                                    ),
                                                )}
                                            </strong>
                                        </p>
                                    </Form.Item>
                                )}
                                <Form.Item wrapperCol={{ offset: 6 }} hidden={!isBannerLessConsent}>
                                    <Notices
                                        notices={[
                                            {
                                                message:
                                                    isBannerLessConsent &&
                                                    jsxJoin(
                                                        [
                                                            _i(
                                                                __(
                                                                    "You have decided to obtain consent without cookie banners (banner-less consent) on your website by activating {{a}}Banner-less consent{{/a}}. This means that your website visitors cannot consent to the purposes of TCF vendors in the cookie banner, as no cookie banner is displayed. As a result, most advertising partners will not be able to display any or only very limited advertising, which {{strong}}will generate significantly less revenue{{/strong}}.",
                                                                ),
                                                                {
                                                                    a: <a href="#/settings/consent" />,
                                                                    strong: <strong />,
                                                                },
                                                            ),
                                                            _i(
                                                                __(
                                                                    "According to the {{a}}TCF Policy Appendix B D. a.{{/a}}, you must also ensure that the privacy settings on each subpage are easily accessible (e.g. {{aLinks}}place legal links in the footer{{/aLinks}}) so that you do not violate the terms of the standard.",
                                                                ),
                                                                {
                                                                    a: (
                                                                        <a
                                                                            href={__(
                                                                                "https://iabeurope.eu/iab-europe-transparency-consent-framework-policies/#headline-2055-18959",
                                                                            )}
                                                                            target="_blank"
                                                                            rel="noreferrer"
                                                                        />
                                                                    ),
                                                                    aLinks: (
                                                                        <a
                                                                            href="#/consent/legal"
                                                                            target="_blank"
                                                                            rel="noreferrer"
                                                                        />
                                                                    ),
                                                                },
                                                            ),
                                                            <strong key="against">
                                                                {__(
                                                                    "We advise against using the Transparency & Consent Framework together with banner-less consent!",
                                                                )}
                                                            </strong>,
                                                        ],
                                                        <>
                                                            <br />
                                                            <br />
                                                        </>,
                                                    ),
                                                severity: "warning",
                                            },
                                        ]}
                                    />
                                </Form.Item>
                                <Form.Item
                                    wrapperCol={{ offset: 6 }}
                                    name="tcfCheckboxTerms"
                                    valuePropName="checked"
                                    style={{ marginBottom: 15 }}
                                    rules={[
                                        {
                                            type: "boolean",
                                            required: true,
                                            transform: (value) => value || undefined,
                                            message: __("Please confirm that you have read the terms!"),
                                        },
                                    ]}
                                >
                                    <Checkbox disabled={isTcfPersisted}>
                                        {_i(
                                            _x(
                                                "I have read, agree to, and will fully comply with the {{aPolicies}}IAB Europe Transparency & Consent Framework Policies{{/aPolicies}} and {{aTerms}}Terms and Conditions for the IAB Europe Transparency & Consent Framework{{/aTerms}}.",
                                                "legal-text",
                                            ),
                                            {
                                                aPolicies: (
                                                    <a
                                                        href={__(
                                                            "https://iabeurope.eu/iab-europe-transparency-consent-framework-policies/",
                                                        )}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                                aTerms: (
                                                    <a
                                                        href={__(
                                                            "https://iabeurope.eu/iab-europe-transparency-consent-framework-terms-conditions/",
                                                        )}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                            },
                                        )}
                                    </Checkbox>
                                </Form.Item>
                                <Form.Item
                                    wrapperCol={{ offset: 6 }}
                                    name="tcfCheckboxVisually"
                                    valuePropName="checked"
                                    rules={[
                                        {
                                            type: "boolean",
                                            required: true,
                                            transform: (value) => value || undefined,
                                            message: __("Please confirm that you agree to the visual changes!"),
                                        },
                                    ]}
                                >
                                    <Checkbox disabled={isTcfPersisted}>
                                        {_x(
                                            "I know that enabling TCF mode will change my consent management (cookie banner) visually as well as functionally. Some options of Real Cookie Banner may be limited to be compliant with the guidelines of the TCF standard.",
                                            "legal-text",
                                        )}
                                    </Checkbox>
                                </Form.Item>
                                <Form.Item label={__("Country of the website operator")} required>
                                    <Form.Item
                                        noStyle
                                        name="operatorCountry"
                                        rules={[
                                            {
                                                required: true,
                                                transform: (value) => value || undefined,
                                                message: __("Please choose the country of origin of your company!"),
                                            },
                                        ]}
                                    >
                                        <Select showSearch optionFilterProp="children">
                                            {Object.keys(iso3166OneAlpha2).map((code) => (
                                                <Select.Option value={code} key={code}>
                                                    {iso3166OneAlpha2[code]}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                    <p className="description">
                                        {__(
                                            "The country whose law applies to the operation of your website. Commonly, this corresponds to the country in which your business is established.",
                                        )}
                                    </p>
                                </Form.Item>
                                {isTcfPersisted && (
                                    <Form.Item label={__("Global Vendor List (GVL)")}>
                                        <Spin spinning={isUpdateDatabaseBusy}>
                                            <button type="button" className="button" onClick={handleUpdateGvl}>
                                                {__("Update now")}
                                            </button>
                                        </Spin>
                                        {tcfGvlDownloadTime ? (
                                            <p style={{ margin: "10px 0 0 0" }}>
                                                <strong>
                                                    {__(
                                                        "You have downloaded the GVL the last time on %s",
                                                        new Date(tcfGvlDownloadTime).toLocaleString(
                                                            document.documentElement.lang,
                                                        ),
                                                    )}
                                                </strong>
                                            </p>
                                        ) : (
                                            <div
                                                className="notice notice-error inline below-h2 notice-alt"
                                                style={{ margin: "10px 0 0 0" }}
                                            >
                                                <p>
                                                    {__(
                                                        "Something seems to have gone wrong when downloading the GVL. Please check if your server has a firewall configured and is blocking the download accordingly, or contact our support!",
                                                    )}
                                                </p>
                                            </div>
                                        )}
                                        <p className="description">
                                            {_i(
                                                __(
                                                    "The {{a}}Global Vendor List (GVL){{/a}} contains all vendors registered with IAB Europe that can receive consents via TCF standard. This list is downloaded to your database so that technical and legal data about the vendors is known and you can select from it. The GVL will be automatically updated every week on Thursdays at 5:00 PM (CET) (published once a week by IAB Europe). {{strong}}In case of any changes in the texts or information of the activated vendors, Real Cookie Banner will automatically obtain new consent from all your visitors.{{/strong}}",
                                                ),
                                                {
                                                    strong: <strong />,
                                                    a: (
                                                        <a
                                                            href={__("https://iabeurope.eu/vendor-list/")}
                                                            rel="noreferrer"
                                                            target="_blank"
                                                        />
                                                    ),
                                                },
                                            )}
                                        </p>
                                    </Form.Item>
                                )}
                            </>
                        )
                    );
                }}
            </Form.Item>
        </>
    );
};

export { FormSettingsTcfTabContent };
