import { Checkbox, Col, Form, Input, Popconfirm, Radio, Row, Select, Space, Switch, Tag, Tooltip } from "antd";
import { useRef } from "react";

import { LABEL_GTM, LABEL_MTM } from "@devowl-wp/cookie-consent-web-client";
import { deepClone } from "@devowl-wp/react-utils";

import { FormSettingsGeneralNavTable } from "./navTable.js";
import { useFormSettings } from "../../../contexts/formSettings.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useUpsell } from "../../../contexts/upsell.js";
import { useNavLinksPageTypes } from "../../../hooks/useNavLinksPageTypes.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";

type FormSettingsGeneralPagePrivacyPolicyMentionUsageStatus = "unset" | "not-in-text" | "in-text" | "show-suggestion";

const useCreateCookiePolicyPageButton = () => {
    const { createCookiePolicy } = useFormSettings();
    const availablePageTypes = useNavLinksPageTypes();
    const { getFieldValue, setFieldsValue } = Form.useFormInstance<FormSettingsValueProps>();

    return async () => {
        const { pageId, onNewNavLinks } = await createCookiePolicy();
        const bannerLinksClone = deepClone(getFieldValue("navLinks") as FormSettingsValueProps["navLinks"]);

        // Remove existing cookie policy link in footer links
        const cookiePolicyIdx = bannerLinksClone.findIndex(({ pageType }) => pageType === "cookiePolicy");
        if (cookiePolicyIdx > -1) {
            bannerLinksClone.splice(cookiePolicyIdx, 1);
        }

        // Add new cookie policy link in footer links
        const privacyPolicyIdx = bannerLinksClone.findIndex(({ pageType }) => pageType === "privacyPolicy");
        bannerLinksClone.splice(privacyPolicyIdx + 1, 0, {
            isExternalUrl: false,
            isTargetBlank: true,
            hideCookieBanner: true,
            pageId,
            pageType: "cookiePolicy",
            label: availablePageTypes.find(({ name }) => name === "cookiePolicy").label,
        });
        setFieldsValue({
            cookiePolicyId: pageId,
            navLinks: bannerLinksClone,
        });

        await onNewNavLinks?.(bannerLinksClone);
    };
};

const FormSettingsGeneralCreateCookiePolicyPageButton: FC = () => {
    const { __ } = useI18n();
    const handleCreateCookiePolicy = useCreateCookiePolicyPageButton();

    return (
        <Popconfirm
            title={__(
                "I am aware that the texts in the cookie policy are suggested formulations and that the manufacturer of Real Cookie Banner cannot take any liability for the topicality, correctness or completeness of the information. I will check the information on my own responsibility, added missing information and correct information that does not fit to my specific use case on my own responsibility.",
            )}
            cancelText={__("Cancel")}
            okText={__("Create page")}
            overlayStyle={{ maxWidth: 450 }}
            onConfirm={handleCreateCookiePolicy}
            placement="bottomLeft"
        >
            <button className="button" type="button" style={{ margin: "2px 0" }}>
                {__("Create page")}
            </button>
        </Popconfirm>
    );
};

const FormSettingsGeneralTabContent: FC = () => {
    const { __, _x, _i } = useI18n();
    const { isPro } = useUpsell();
    const {
        iso3166OneAlpha2,
        renderPageSelector: RenderPageSelector,
        deactivateCookiePolicy,
        onCustomizeClick,
    } = useFormSettings();
    const cookiePolicyUrl = useRef<string>();

    return (
        <>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, nextValues) => prevValues.isBannerActive !== nextValues.isBannerActive}
            >
                {({ getFieldValue, setFieldsValue }) => {
                    const isBannerActive = getFieldValue("isBannerActive") as boolean;

                    return (
                        <>
                            <Form.Item label={__("Cookie Banner/Dialog")}>
                                <Form.Item noStyle name="isBannerActive" valuePropName="checked">
                                    <Switch style={{ display: isBannerActive ? undefined : "none" }} />
                                </Form.Item>
                                {!isBannerActive && (
                                    <Popconfirm
                                        title={_x(
                                            "I am aware that the texts in the cookie banner and content blocker are suggested formulations and that the manufacturer of Real Cookie Banner cannot take any liability for the topicality, correctness or completeness of the information. I have checked the information on my own responsibility, added missing information and correct information that does not fit to my specific use case on my own responsibility.",
                                            "legal-text",
                                        )}
                                        cancelText={__("Cancel")}
                                        okText={__("Activate now!")}
                                        overlayStyle={{ maxWidth: 450 }}
                                        onCancel={() => {
                                            setFieldsValue({ isBannerActive: false });
                                        }}
                                        onConfirm={() => {
                                            setFieldsValue({ isBannerActive: true });
                                        }}
                                        placement="bottomLeft"
                                    >
                                        <Switch checked={false} />
                                    </Popconfirm>
                                )}
                                <p className="description" style={{ marginTop: 5 }}>
                                    {__(
                                        "You can enable and disable the cookie banner. We recommend to activate the cookie banner on your website after you have added all services.",
                                    )}
                                </p>
                            </Form.Item>
                            <Form.Item
                                label={__("Content Blocker")}
                                style={{ display: isBannerActive ? undefined : "none" }}
                            >
                                <Form.Item name="isBlockerActive" valuePropName="checked" noStyle>
                                    <Switch style={{ marginTop: 5 }} />
                                </Form.Item>
                                <p className="description" style={{ marginTop: 5 }}>
                                    {__(
                                        "This feature allows you to block content that would process personal data and set cookies, but for which you do not yet have the visitor's consent.",
                                    )}
                                </p>
                            </Form.Item>
                        </>
                    );
                }}
            </Form.Item>
            <Form.Item label={__("Website operator details")}>
                <p className="description" style={{ marginTop: 7, marginBottom: 12 }}>
                    {__(
                        "You as a website operator should provide your address and at least one digital contact option to fulfill your information obligations for self-hosted services. If you have a company with subsidiaries, please disclose the company that is responsible for the data processing on their website.",
                    )}
                </p>
                <Row gutter={[10, 10]}>
                    <Col span={24}>
                        <Form.Item name="operatorContactAddress" style={{ margin: 0 }}>
                            <Input
                                addonBefore={__("Full address")}
                                placeholder={__(
                                    "e.g. Global Co., 90210 Broadway Blvd., Nashville, TN 37011-5678 (without country)",
                                )}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Space.Compact className="rcb-antd-select-addon">
                            <Input addonBefore={__("Country")} />
                            <Form.Item name="operatorCountry" noStyle>
                                <Select showSearch optionFilterProp="children">
                                    {Object.keys(iso3166OneAlpha2).map((code) => (
                                        <Select.Option value={code} key={code}>
                                            {iso3166OneAlpha2[code]}
                                        </Select.Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Space.Compact>
                    </Col>
                    <Col span={12}>
                        <Form.Item name="operatorContactPhone" style={{ margin: 0 }}>
                            <Input addonBefore={__("Phone")} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="operatorContactEmail"
                            rules={[{ type: "email", message: __("Please provide a valid email!") }]}
                            style={{ margin: 0 }}
                        >
                            <Input addonBefore={__("Email")} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Space.Compact className="rcb-antd-select-addon">
                            <Input addonBefore={__("Contact form")} />
                            <Form.Item name="operatorContactFormId" noStyle>
                                <RenderPageSelector
                                    id="operatorContactFormId"
                                    disabled={false}
                                    multiple={false}
                                    onlyPages={true}
                                />
                            </Form.Item>
                        </Space.Compact>
                    </Col>
                </Row>
            </Form.Item>
            <Form.Item label={__("Legal basis to be applied")}>
                <Form.Item
                    name="territorialLegalBasis"
                    noStyle
                    rules={[{ required: true, message: __("Please choose at least one legal basis to apply!") }]}
                >
                    <Checkbox.Group style={{ marginTop: 5 }}>
                        <Checkbox value="gdpr-eprivacy">{__("GDPR / ePrivacy Directive")}</Checkbox>
                        <Checkbox value="dsg-switzerland">
                            {__("DSG (Switzerland)")}{" "}
                            <LearnMoreTag
                                url={__("https://devowl.io/knowledge-base/cookie-banner-swiss-data-protection-fadp/")}
                            />
                        </Checkbox>
                    </Checkbox.Group>
                </Form.Item>
                <p className="description" style={{ marginBottom: 0 }}>
                    {__(
                        "Your website, and consequently the cookie banner, can be aligned to different legal bases. If you select multiple legal bases, suggestions in the settings will always match the stricter legal basis.",
                    )}
                </p>
            </Form.Item>
            <Form.Item<FormSettingsValueProps>
                label={__("Cookie policy page")}
                shouldUpdate={({ cookiePolicyId: a }, { cookiePolicyId: b }) => a !== b}
            >
                {({ getFieldValue, setFieldsValue }) => {
                    const cookiePolicyId = getFieldValue("cookiePolicyId") as FormSettingsValueProps["cookiePolicyId"];

                    return (
                        <>
                            <div style={{ display: cookiePolicyId > 0 ? "block" : "none", maxWidth: 400 }}>
                                <Space.Compact className="rcb-antd-select-addon">
                                    <Form.Item<FormSettingsValueProps> name="cookiePolicyId" noStyle>
                                        <RenderPageSelector
                                            id="cookiePolicyId"
                                            disabled={true}
                                            multiple={false}
                                            onlyPages={true}
                                            selectedPageUrl={(url) => {
                                                cookiePolicyUrl.current = url;
                                            }}
                                        />
                                    </Form.Item>
                                    <Input
                                        addonAfter={
                                            <>
                                                <a onClick={() => onCustomizeClick("rcb-cookie-policy-instruction")}>
                                                    {__("Customize")}
                                                </a>
                                                &nbsp;&bull;&nbsp;
                                                <a onClick={() => window.open(cookiePolicyUrl.current, "_blank")}>
                                                    {__("Open page")}
                                                </a>
                                                &nbsp;&bull;&nbsp;
                                                <Popconfirm
                                                    title={__(
                                                        "If you want to deactivate the cookie policy page, the page created for it will also be deleted.",
                                                    )}
                                                    cancelText={__("Cancel")}
                                                    okText={__("Deactivate and delete page")}
                                                    onConfirm={async () => {
                                                        const { onNewNavLinks } =
                                                            await deactivateCookiePolicy(cookiePolicyId);

                                                        const newNavLinks = (
                                                            getFieldValue(
                                                                "navLinks",
                                                            ) as FormSettingsValueProps["navLinks"]
                                                        ).filter(({ pageType }) => pageType !== "cookiePolicy");
                                                        setFieldsValue({
                                                            cookiePolicyId: 0,
                                                            navLinks: newNavLinks,
                                                        });

                                                        await onNewNavLinks?.(newNavLinks);
                                                    }}
                                                    overlayStyle={{ maxWidth: 450 }}
                                                    placement="bottomLeft"
                                                >
                                                    <a>{__("Deactivate")}</a>
                                                </Popconfirm>
                                            </>
                                        }
                                    />
                                </Space.Compact>
                            </div>
                            {!cookiePolicyId && <FormSettingsGeneralCreateCookiePolicyPageButton />}
                            <div style={{ margin: "5px 0px 0px" }}>
                                <LearnMoreTag
                                    url={__("https://devowl.io/knowledge-base/cookie-policy-wordpress-website/")}
                                />
                            </div>
                            <p className="description" style={{ marginBottom: 0 }}>
                                {_i(
                                    __(
                                        "A cookie policy is a document that lists all the cookies and similar instruments used on a website and provides comprehensive information about each cookie. There is {{strong}}no obligation{{/strong}} to create a cookie policy under the GDPR or the ePrivacy Directive. But it can help you to present the handling of cookies and cookie-like technologies to your website visitors transparently and separately from your privacy policy.",
                                    ),
                                    { strong: <strong /> },
                                )}
                            </p>
                        </>
                    );
                }}
            </Form.Item>
            <Form.Item label={__("Footer links")}>
                <p className="description" style={{ marginTop: 7, marginBottom: 12 }}>
                    {__(
                        "According to the ePrivacy Directive, legally required pages such as the privacy policy may be accessible without the user having to give consent to services and their cookies. Therefore, it is recommended to avoid processing personal data and setting cookies on these pages and not to display a cookie banner, but add those links to the footer of the cookie banner. Content blockers block loading of scripts etc. even on pages where the cookie banner is not displayed.",
                    )}
                </p>
                <FormSettingsGeneralNavTable />
            </Form.Item>
            <Form.Item<FormSettingsValueProps>
                noStyle
                shouldUpdate={(prevValues, nextValues) =>
                    prevValues.isBannerLessConsent !== nextValues.isBannerLessConsent
                }
            >
                {({ getFieldValue }) => {
                    const isBannerLessConsent = getFieldValue(
                        "isBannerLessConsent",
                    ) as FormSettingsValueProps["isBannerLessConsent"];

                    return (
                        <Form.Item label={__("Hide cookie banner on specific pages")}>
                            <Tooltip
                                title={
                                    isBannerLessConsent
                                        ? _i(
                                              __(
                                                  "The cookie banner is hidden on all subpages due to the active option {{a}}Consent > Banner-less consent{{/a}}.",
                                              ),
                                              {
                                                  a: (
                                                      <a
                                                          href="#/settings/consent"
                                                          style={{
                                                              fontStyle: "italic",
                                                          }}
                                                      />
                                                  ),
                                              },
                                          )
                                        : undefined
                                }
                            >
                                <Space.Compact className="rcb-antd-select-addon">
                                    <Input
                                        addonBefore={
                                            <>
                                                {__("Hide on additional pages")}&nbsp;
                                                <UpsellTag
                                                    title={__("Want to hide cookie banner on more pages?")}
                                                    testDrive
                                                    feature="hide-page-ids"
                                                    description={__(
                                                        "Cookie banners are legally necessary, but distract your users from the essentials. For example, on landing pages for advertising campaigns, they lead to lower conversion rates. On these pages, it can be useful to avoid processing personal data and setting cookies to keep the conversion rate high. You can hide the cookie banner on these pages.",
                                                    )}
                                                />
                                            </>
                                        }
                                    />
                                    <Form.Item name="hidePageIds" noStyle>
                                        <RenderPageSelector
                                            id="hidePageIds"
                                            disabled={!isPro || isBannerLessConsent}
                                            multiple={true}
                                        />
                                    </Form.Item>
                                </Space.Compact>
                            </Tooltip>
                        </Form.Item>
                    );
                }}
            </Form.Item>
            <Form.Item label={__("Load services after consent via")}>
                <Form.Item<FormSettingsValueProps>
                    noStyle
                    shouldUpdate={(prevValues, nextValues) => prevValues.isGcm !== nextValues.isGcm}
                >
                    {({ getFieldValue }) => (
                        <Form.Item name="setCookiesViaManager" noStyle>
                            <Radio.Group>
                                <Space direction="vertical">
                                    <Radio disabled={!isPro} value="none">
                                        {__("HTML/JavaScript Snippet")}
                                    </Radio>
                                    <Tooltip
                                        title={
                                            isPro &&
                                            !getFieldValue("isGcm") &&
                                            _i(
                                                __(
                                                    "In order to be able to transfer consents to Google Tag Manager via Google Consent Mode, please activate this standard first under {{a}}Settings > Google Consent Mode{{/a}}.",
                                                ),
                                                {
                                                    a: <a href="#/settings/gcm" />,
                                                },
                                            )
                                        }
                                    >
                                        <Radio
                                            disabled={!isPro || !getFieldValue("isGcm")}
                                            value="googleTagManagerWithGcm"
                                        >
                                            {__("Google Tag Manager with Google Consent Mode")}
                                            &nbsp;
                                            <LearnMoreTag
                                                url={__(
                                                    "https://devowl.io/knowledge-base/real-cookie-banner-with-google-tag-manager-google-consent-mode/",
                                                )}
                                            />
                                        </Radio>
                                    </Tooltip>
                                    <Radio disabled={!isPro} value="googleTagManager">
                                        {__("%s Event", LABEL_GTM)}
                                        &nbsp;
                                        <LearnMoreTag
                                            url={__(
                                                "https://devowl.io/knowledge-base/real-cookie-banner-with-google-tag-manager-or-matomo-tag-manager/",
                                            )}
                                        />
                                        <Tooltip title={__("Use Google Tag Manager with Google Consent Mode instead.")}>
                                            <Tag>{__("Deprecated")}</Tag>
                                        </Tooltip>
                                    </Radio>
                                    <Radio disabled={!isPro} value="matomoTagManager">
                                        {__("%s Event", LABEL_MTM)}
                                        &nbsp;
                                        <LearnMoreTag
                                            url={__(
                                                "https://devowl.io/knowledge-base/real-cookie-banner-with-google-tag-manager-or-matomo-tag-manager/",
                                            )}
                                        />
                                    </Radio>
                                </Space>
                            </Radio.Group>
                        </Form.Item>
                    )}
                </Form.Item>
                <div style={{ margin: "5px 0px 0px" }}>
                    <UpsellTag
                        title={__("Want to use a Tag Manager legally?")}
                        testDrive
                        feature="set-cookies-via-manager"
                        assetName={__("pro-modal/set-cookies-via-manager.png")}
                        description={__(
                            "You can integrate services via Google Tag Manager or Matomo Tag Manager. At the same time, you can obtain and document consents via Real Cookie Banner in accordance with data protection regulations.",
                        )}
                    />
                </div>
                <p className="description">
                    <strong>
                        {__("You only need to change this option if you use Google Tag Manager or Matomo Tag Manager.")}
                    </strong>
                    &nbsp;
                    {_i(
                        __(
                            "If you opt-in to or opt-out from services, you will normally execute JavaScript code to ensure that scripts are enabled/disabled and cookies are set/removed on the visitor's client. If you use Google Tag Manager or Matomo Tag Manager, you can map this behavior using tags. However, even if they are executed via the tag manager, the tags may only be fired if consent has been given for the respective service. Real Cookie Banner can automatically transmit the consent to the respective Tag Manager via events or Google Consent Mode (recommended).",
                        ),
                        {
                            strong: <strong />,
                        },
                    )}
                </p>
            </Form.Item>
        </>
    );
};

export {
    useCreateCookiePolicyPageButton,
    FormSettingsGeneralTabContent,
    type FormSettingsGeneralPagePrivacyPolicyMentionUsageStatus,
    FormSettingsGeneralCreateCookiePolicyPageButton,
};
