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

import { useFormSettings } from "../../../contexts/formSettings.js";
import { useI18n } from "../../../contexts/i18n.js";
import { useUpsell } from "../../../contexts/upsell.js";
import { UpsellTag } from "../../upsell/tag.js";

import type { FC } from "react";

const FormSettingsCountryBypassTabContent: FC = () => {
    const { message } = App.useApp();
    const { __, _x, _i } = useI18n();
    const { isPro, isLicensed } = useUpsell();
    const {
        isCountryBypass: isCountryBypassPersisted,
        countryBypassDbDownloadTime,
        onCountryBypassUpdateDatabase,
        iso3166OneAlpha2,
        predefinedCountryBypassLists,
    } = useFormSettings();
    const [isUpdateDatabaseBusy, setUpdateDatabaseBusy] = useState(false);

    const handleUpdateDatabase = useCallback(async () => {
        setUpdateDatabaseBusy(true);
        try {
            await onCountryBypassUpdateDatabase();
            message.success(__("You successfully updated the IP-to-Country database."));
        } catch (e) {
            message.error(e.responseJSON.message);
            throw e;
        } finally {
            setUpdateDatabaseBusy(false);
        }
    }, [onCountryBypassUpdateDatabase]);

    const getLabelForPredefinedCountryList = useCallback((code: string) => {
        if (code === "GDPR") {
            return __("Countries where GDPR applies");
        }

        return __("Countries where %s applies", code);
    }, []);

    return (
        <>
            <Form.Item label={__("Geo-restriction")} style={{ marginBottom: 10 }}>
                <Form.Item name="isCountryBypass" 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 IP-to-Country database 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" }}>
                    <UpsellTag
                        title={__("Enable geo-restriction?")}
                        testDrive
                        feature="country-bypass"
                        assetName={__("pro-modal/geo-restriction.png")}
                        description={__(
                            "Cookie banners must be displayed only to visitors from certain countries. For example, visitors from the EU. With geo-restriction you can specify exactly who sees a cookie banner and who doesn't, by country.",
                        )}
                    />
                </div>
                <p className="description">
                    {__(
                        `With the geo-restrictions you can specify that the cookie banner should be displayed only for users from certain countries. In many countries (outside the EU) it is not necessary to display a cookie banner. The location of the user is determined by their IP address.`,
                    )}
                </p>
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, curValues) => prevValues.isCountryBypass !== curValues.isCountryBypass}
            >
                {({ getFieldValue }) => {
                    const isCountryBypass = getFieldValue("isCountryBypass") as boolean;

                    return (
                        isPro &&
                        isCountryBypass && (
                            <>
                                <Form.Item
                                    wrapperCol={{ offset: 6 }}
                                    name="countryBypassCheckboxTerms"
                                    valuePropName="checked"
                                    style={{ marginBottom: 15 }}
                                    rules={[
                                        {
                                            type: "boolean",
                                            required: true,
                                            transform: (value) => value || undefined,
                                            message: __("Please confirm that you have read this!"),
                                        },
                                    ]}
                                >
                                    <Checkbox disabled={isCountryBypassPersisted}>
                                        {_i(
                                            _x(
                                                "To determine the location of your website visitors, the MaxMind GeoLite2 database will be downloaded to your server and used from there. I have read and agree to the {{aMaxMindEndUserLicense}}MaxMind End User License Agreement{{/aMaxMindEndUserLicense}}. The download of the database is done via a devowl.io server and I agree to the {{aTerms}}terms and conditions{{/aTerms}} and {{aPrivacyPolicy}}privacy policy{{/aPrivacyPolicy}}.",
                                                "legal-text",
                                            ),
                                            {
                                                aMaxMindEndUserLicense: (
                                                    <a
                                                        href={__(
                                                            "https://www.maxmind.com/en/end-user-license-agreement",
                                                        )}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                                aTerms: (
                                                    <a
                                                        href={__("https://devowl.io/terms/")}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                                aPrivacyPolicy: (
                                                    <a
                                                        href={__("https://devowl.io/privacy-policy/")}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                            },
                                        )}
                                    </Checkbox>
                                </Form.Item>
                                <Form.Item
                                    wrapperCol={{ offset: 6 }}
                                    name="countryBypassCheckboxAccuracy"
                                    valuePropName="checked"
                                    style={{ marginBottom: 15 }}
                                    rules={[
                                        {
                                            type: "boolean",
                                            required: true,
                                            transform: (value) => value || undefined,
                                            message: __("Please confirm that you have read this!"),
                                        },
                                    ]}
                                >
                                    <Checkbox disabled={isCountryBypassPersisted}>
                                        {_i(
                                            _x(
                                                "I understand that this type of location determination is not accurate with one hundred percent certainty. According to {{a}}MaxMind's data{{/a}}, 99.8%% accuracy is estimated without obligation.",
                                                "legal-text",
                                            ),
                                            {
                                                a: (
                                                    <a
                                                        href={__(
                                                            "https://support.maxmind.com/hc/en-us/articles/4407630607131-Geolocation-Accuracy",
                                                        )}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                            },
                                        )}
                                    </Checkbox>
                                </Form.Item>
                                <Form.Item label={__("Show banner only to users from these countries")}>
                                    <Form.Item name="countryBypassCountries" noStyle>
                                        <Select mode="multiple" showSearch optionFilterProp="children">
                                            {Object.keys(predefinedCountryBypassLists).map((code) => {
                                                const label = getLabelForPredefinedCountryList(code);
                                                return (
                                                    label && (
                                                        <Select.Option value={code} key={code}>
                                                            {label}
                                                        </Select.Option>
                                                    )
                                                );
                                            })}
                                            {Object.keys(iso3166OneAlpha2).map((code) => (
                                                <Select.Option value={code} key={code}>
                                                    {iso3166OneAlpha2[code]}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                    <p className="description">
                                        {__(
                                            "Determines for users from which countries you want to display a cookie banner. It is recommended to display cookie banners at least in the countries where the GDPR and CCPA apply. The list of countries can be extended at any time by the accession of new countries (Last update: October 2023).",
                                        )}
                                    </p>
                                    {Object.keys(predefinedCountryBypassLists).map((code) => {
                                        const label = getLabelForPredefinedCountryList(code);
                                        return (
                                            label && (
                                                <p className="description" key={code}>
                                                    <strong>{label}: </strong>
                                                    {predefinedCountryBypassLists[code]
                                                        .map((cc) => iso3166OneAlpha2[cc])
                                                        .join(", ")}
                                                </p>
                                            )
                                        );
                                    })}
                                </Form.Item>
                                <Form.Item
                                    label={__("Implicit consent for users from third countries")}
                                    style={{ marginBottom: 10 }}
                                >
                                    <Form.Item name="countryBypassType" noStyle>
                                        <Radio.Group>
                                            <Radio.Button value="all">{__("Accept all")}</Radio.Button>
                                            <Radio.Button value="essentials">
                                                {__("Accept only essentials")}
                                            </Radio.Button>
                                        </Radio.Group>
                                    </Form.Item>
                                    <p className="description">
                                        {__(
                                            `Set what consent should be implied when a visitor is not shown a cookie banner.`,
                                        )}
                                    </p>
                                </Form.Item>
                                {isCountryBypassPersisted && (
                                    <>
                                        <Form.Item label={__("IP-to-Country database")}>
                                            <Spin spinning={isUpdateDatabaseBusy}>
                                                <button type="button" className="button" onClick={handleUpdateDatabase}>
                                                    {__("Update now")}
                                                </button>
                                            </Spin>
                                            {countryBypassDbDownloadTime ? (
                                                <p style={{ margin: "10px 0 0 0" }}>
                                                    <strong>
                                                        {__(
                                                            "You have downloaded the IP-to-Country database the last time on %s",
                                                            new Date(countryBypassDbDownloadTime).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 IP-to-Country database. Please check if your server has a firewall configured and is blocking the download accordingly, or contact our support!",
                                                        )}
                                                    </p>
                                                </div>
                                            )}
                                            <p className="description">
                                                {__(
                                                    "The IP-to-Country database contains a huge set of IP ranges where we can look up where the current user is coming from based on a specific IP address.",
                                                )}
                                            </p>
                                        </Form.Item>
                                    </>
                                )}
                            </>
                        )
                    );
                }}
            </Form.Item>
        </>
    );
};

export { FormSettingsCountryBypassTabContent };
