import { App, Empty, Form, Input, Radio, Select } from "antd";
import { useCallback, useState } from "react";

import { copyToClipboard, useAsyncEffect } 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 { UpsellTag } from "../../upsell/tag.js";

import type { DOMAttributes, FC } from "react";

const FormSettingsMultisiteTabContent: FC = () => {
    const { message } = App.useApp();
    const { __, _i } = useI18n();
    const { isPro } = useUpsell();
    const {
        isTcf,
        multisiteEndpoints: { current, forwardTo },
        fetchMultisiteEndpoints,
    } = useFormSettings();

    const [isFetchingEndpoints, setFetchingEndpoints] = useState(false);

    useAsyncEffect(async () => {
        setFetchingEndpoints(true);
        try {
            await fetchMultisiteEndpoints();
        } catch (e) {
            message.error(e.responseJSON.message);
            throw e;
        } finally {
            setFetchingEndpoints(false);
        }
    }, []);

    const handleCurrentEndpointCopy: DOMAttributes<HTMLButtonElement>["onClick"] = useCallback((e) => {
        copyToClipboard(
            ((e.target as HTMLButtonElement).parentElement.previousElementSibling as HTMLInputElement).value,
        );
        message.success(__("Successfully copied to the clipboard!"));
        e.preventDefault();
        return false;
    }, []);

    return (
        <>
            <Form.Item label={__("Consent Forwarding")}>
                <Form.Item name="isConsentForwarding" 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" }}>
                    <LearnMoreTag
                        url={__("https://devowl.io/knowledge-base/cookie-banner-consent-forwarding-setup/")}
                    />
                    <UpsellTag
                        title={__("One consent for all your websites?")}
                        testDrive
                        feature="consent-forwarding"
                        assetName={__("pro-modal/consent-forwarding.png")}
                        description={__(
                            "In WordPress multisites or multiple instances of WordPress running for one organization, you only need to obtain consent once. Consents are automatically forwarded, so your visitor only needs to accept services and cookies once, instead of on each site again.",
                        )}
                    />
                </div>
                <p className="description">
                    {__(
                        `You can ask the user for consent on one site, and the consent applies to other sites in a WordPress multisite installation or other standalone WordPress installations. This is useful if you run multiple WordPress sites for one organization. For example, you have a company page, landing page, and blog, and you want to show the user as few cookie banners as possible.`,
                    )}
                </p>
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, curValues) =>
                    prevValues.isConsentForwarding !== curValues.isConsentForwarding
                }
            >
                {({ getFieldValue }) => {
                    const isConsentForwarding = getFieldValue("isConsentForwarding") as boolean;

                    return (
                        isPro &&
                        isConsentForwarding && (
                            <>
                                {isTcf && (
                                    <Form.Item wrapperCol={{ offset: 6 }}>
                                        <div
                                            className="notice notice-info inline below-h2 notice-alt"
                                            style={{ margin: 0 }}
                                        >
                                            <p>
                                                {__(
                                                    "Please note that in all sites that are provided with consent forwarding, you must use exactly the same TCF vendors with the same settings (vendor restrictions). If there are any discrepancies, the consent in the TCF standardized consent (TC string) will overwrite each other according to its specification.",
                                                )}
                                            </p>
                                        </div>
                                    </Form.Item>
                                )}
                                <Form.Item
                                    noStyle
                                    shouldUpdate={(prevValues, nextValues) =>
                                        JSON.stringify(prevValues.forwardTo) !== JSON.stringify(nextValues.forwardTo) ||
                                        JSON.stringify(prevValues.crossDomains) !==
                                            JSON.stringify(nextValues.crossDomains)
                                    }
                                >
                                    {({ getFieldValue }) =>
                                        (
                                            JSON.stringify(getFieldValue("forwardTo")) +
                                            JSON.stringify(getFieldValue("crossDomains"))
                                        ).indexOf("http://") > -1 && (
                                            <Form.Item wrapperCol={{ offset: 6 }}>
                                                <div
                                                    className="notice notice-warning inline below-h2 notice-alt"
                                                    style={{ margin: 0 }}
                                                >
                                                    <p>
                                                        {_i(
                                                            __(
                                                                "One of your configured endpoints is using an insecure protocol (not HTTPS). For security reasons, most modern browsers reject and block the use of cross-domain cookies on unsecured pages. {{a}}Learn more.{{/a}}",
                                                            ),
                                                            {
                                                                a: (
                                                                    <a
                                                                        href={__(
                                                                            "https://www.chromestatus.com/feature/5633521622188032",
                                                                        )}
                                                                        rel="noreferrer"
                                                                        target="_blank"
                                                                    />
                                                                ),
                                                            },
                                                        )}
                                                    </p>
                                                </div>
                                            </Form.Item>
                                        )
                                    }
                                </Form.Item>
                                <Form.Item label={__("Forward to")}>
                                    <Form.Item name="forwardTo" noStyle>
                                        <Select
                                            mode="multiple"
                                            notFoundContent={
                                                <Empty description={__("No additional sites endpoints found.")} />
                                            }
                                            filterOption={false}
                                            loading={isFetchingEndpoints}
                                        >
                                            {Object.keys(forwardTo).map((url) => (
                                                <Select.Option key={url} value={url}>
                                                    {forwardTo[url]}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                    <p className="description">
                                        {__(
                                            "Select all sites to which the consent of the user on the current site should be forwarded.",
                                        )}
                                    </p>
                                </Form.Item>
                                <Form.Item label={__("External 'Forward To' endpoints")}>
                                    <Form.Item name="crossDomains" noStyle>
                                        <Input.TextArea autoSize={{ minRows: 3 }} />
                                    </Form.Item>
                                    <p className="description">
                                        {__(
                                            "This option is only required if you want to forward consent to another WordPress installation. Please enter one URL endpoint of the Real Cookie Banner WP REST API per line. Below you find a list of all available endpoints of this WordPress installation.",
                                        )}
                                    </p>
                                    {Object.keys(current).map((url) => (
                                        <p key={url}>
                                            <label>{current[url]}</label>
                                            <Input
                                                value={url}
                                                readOnly
                                                addonAfter={
                                                    <button
                                                        className="button-link alignright"
                                                        onClick={handleCurrentEndpointCopy}
                                                    >
                                                        {__("Copy to clipboard")}
                                                    </button>
                                                }
                                            />
                                        </p>
                                    ))}
                                </Form.Item>
                            </>
                        )
                    );
                }}
            </Form.Item>
        </>
    );
};

export { FormSettingsMultisiteTabContent };
