import { Col, Divider, Row, Tag, Tooltip } from "antd";
import { observer } from "mobx-react";

import type { CommonContextProps } from "@devowl-wp/react-cookie-banner";

import { useStores } from "../../../../store/stores.js";
import { __ } from "../../../../utils/i18n.js";

import type { Consent } from "../../../../models/consent.js";
import type { FC } from "react";

const ConsentTableRecordSettings: FC<{ record: Consent }> = observer(
    ({
        record: {
            forwarded,
            revision: {
                data: { options },
            },
            revision_independent: {
                data: { options: independentOptions },
            },
        },
    }) => {
        const {
            optionStore: {
                others: { pageByIdUrl, iso3166OneAlpha2 },
            },
        } = useStores();
        const useOptions = {
            ...independentOptions,
            ...options,
        };

        return forwarded ? null : (
            <Row>
                <Col span={24}>
                    <Divider>{__("Settings at the time of consent")}</Divider>
                </Col>
                {Object.keys(useOptions).map((key) => {
                    let label = key;
                    let value: any = useOptions[key];
                    let known = true;
                    switch (key as keyof typeof useOptions) {
                        // Ignore this settings, as they are visible with the live preview
                        case "cookieVersion":
                        case "consentDuration":
                            return null;
                        case "isTcf":
                            label = __("Transparency & Consent Framework (TCF)");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "cookiePolicyId":
                            label = __("Cookie Policy Page");
                            value = value ? (
                                <a
                                    href={`${pageByIdUrl}=${value}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    style={{ marginRight: 5 }}
                                >
                                    {__("Open site")} (ID {value})
                                </a>
                            ) : (
                                __("Not defined")
                            );
                            break;
                        case "isGcm":
                            label = __("Google Consent Mode");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isGcmCollectAdditionalDataViaUrlParameters":
                            if (!useOptions.isGcm) {
                                return null;
                            }
                            label = `Google Consent Mode: ${__("Collect additional data via URL parameters")}`;
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isGcmRedactAdsDataWithoutConsent":
                            if (!useOptions.isGcm) {
                                return null;
                            }
                            label = `Google Consent Mode: ${__("Redact ads data without consent")}`;
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isGcmListPurposes":
                            if (!useOptions.isGcm) {
                                return null;
                            }
                            label = `Google Consent Mode: ${__("Naming of requested consent types in first view")}`;
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "operatorCountry":
                            label = __("Website operator country");
                            value = iso3166OneAlpha2[value] || value || __("Not defined");
                            break;
                        case "operatorContactAddress":
                            label = __("Website operator full address");
                            value = value || __("Not defined");
                            break;
                        case "operatorContactEmail":
                            label = __("Website operator email");
                            value = value || __("Not defined");
                            break;
                        case "operatorContactPhone":
                            label = __("Website operator phone");
                            value = value || __("Not defined");
                            break;
                        case "operatorContactFormId":
                            label = __("Contact form page");
                            value = value ? (
                                <a
                                    href={`${pageByIdUrl}=${value}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    style={{ marginRight: 5 }}
                                >
                                    {__("Open site")} (ID {value})
                                </a>
                            ) : (
                                __("Not defined")
                            );
                            break;
                        case "territorialLegalBasis":
                            label = __("Legal basis to be applied");
                            value = (value as (typeof useOptions)["territorialLegalBasis"])
                                .map((legalBasis) => {
                                    switch (legalBasis as CommonContextProps["territorialLegalBasis"][0]) {
                                        case "gdpr-eprivacy":
                                            return __("GDPR / ePrivacy Directive");
                                        case "dsg-switzerland":
                                            return __("DSG (Switzerland)");
                                        default:
                                            return legalBasis;
                                    }
                                })
                                .join(", ");
                            break;
                        case "isBannerActive":
                            label = __("Cookie Banner/Dialog");
                            value = value ? __("Active") : __("Deactivated");
                            break;
                        case "isBlockerActive":
                            label = __("Content Blocker");
                            value = value ? __("Active") : __("Deactivated");
                            break;
                        case "setCookiesViaManager":
                            label = __("Set cookies after consent via");
                            value =
                                value === "googleTagManager" || value === "googleTagManagerWithGcm"
                                    ? "Google Tag Manager"
                                    : value === "matomoTagManager"
                                      ? "Matomo Tag Manager"
                                      : __("Disabled");
                            break;
                        case "isAcceptAllForBots":
                            label = __("Automatically accept all services for bots");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isRespectDoNotTrack":
                            label = __('Respect "Do Not Track"');
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "cookieDuration":
                            label = __("Duration of cookie consent");
                            value = `${value} ${__("days")}`;
                            break;
                        case "failedConsentDocumentationHandling":
                            label = __("Handling of failed consent documentation");
                            switch (value as (typeof independentOptions)["failedConsentDocumentationHandling"]) {
                                case "essentials":
                                    value = __("Allow only essential services");
                                    break;
                                case "optimistic":
                                    value = __("Respect user consent");
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case "isSaveIp":
                            label = __("Save IP address on consent");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isDataProcessingInUnsafeCountries":
                            label = __("Consent for data processing in unsafe third countries");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        // @deprecated
                        case "dataProcessingInUnsafeCountriesSafeCountries":
                            // only show when data processing in unsafe countries was active
                            if (!useOptions.isDataProcessingInUnsafeCountries) {
                                return null;
                            }

                            label = __("Safe countries in terms of the GDPR");
                            if (value) {
                                const countries = (
                                    value as (typeof useOptions)["dataProcessingInUnsafeCountriesSafeCountries"]
                                ).map((code) => iso3166OneAlpha2[code]);
                                value = (
                                    <Tooltip title={countries.join(", ")}>
                                        <Tag>{__("%d countries", countries.length)}</Tag>
                                    </Tooltip>
                                );
                            } else {
                                value = __("Not defined");
                            }
                            break;
                        case "isAgeNotice":
                            label = __("Age notice for consent");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "ageNoticeAgeLimit":
                            // only show when age notice was active
                            if (!useOptions.isAgeNotice) {
                                return null;
                            }

                            label = __("Age limit");
                            break;
                        case "isBannerLessConsent":
                            label = __("Banner-less consent");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "bannerLessConsentShowOnPageIds":
                            if (!useOptions.isBannerLessConsent) {
                                return null;
                            }

                            label = __("Show cookie banner on specific pages");
                            if (value) {
                                value = (value as (typeof useOptions)["bannerLessConsentShowOnPageIds"]).map((id) => (
                                    <a
                                        key={id}
                                        href={`${pageByIdUrl}=${id}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{ marginRight: 5 }}
                                    >
                                        {__("Open site")} (ID {id})
                                    </a>
                                ));
                            }
                            break;
                        case "isListServicesNotice":
                            label = __("Naming of all services in first view");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "isConsentForwarding":
                            label = __("Consent Forwarding");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "forwardTo":
                            label = __("Forward To");
                            if (value) {
                                value = (value as (typeof useOptions)["forwardTo"]).map((url) => (
                                    <a
                                        key={url}
                                        href={url}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{ marginRight: 5 }}
                                    >
                                        {__("Open endpoint")}
                                    </a>
                                ));
                            }
                            value = value?.length ? value : __("Not defined");
                            break;
                        case "crossDomains":
                            label = __("Additional cross domain endpoints");
                            if (value) {
                                value = (value as (typeof useOptions)["crossDomains"]).map((url) => (
                                    <a
                                        key={url}
                                        href={url}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{ marginRight: 5 }}
                                    >
                                        {__("Open endpoint")}
                                    </a>
                                ));
                            }
                            value = value?.length ? value : __("Not defined");
                            break;
                        case "hidePageIds":
                            label = __("Hide on additional pages");
                            if (value) {
                                value = (value as (typeof useOptions)["hidePageIds"]).map((id) => (
                                    <a
                                        key={id}
                                        href={`${pageByIdUrl}=${id}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{ marginRight: 5 }}
                                    >
                                        {__("Open site")} (ID {id})
                                    </a>
                                ));
                            }
                            value = value?.length ? value : __("Not defined");
                            break;
                        case "isCountryBypass":
                            label = __("Geo-restriction");
                            value = value ? __("Enabled") : __("Disabled");
                            break;
                        case "countryBypassCountries":
                            // only show when Country Bypass was active
                            if (!useOptions.isCountryBypass) {
                                return null;
                            }

                            label = __("Show banner only to users from these countries");
                            if (value) {
                                const countries = (value as (typeof useOptions)["countryBypassCountries"]).map(
                                    (code) => iso3166OneAlpha2[code],
                                );
                                value = (
                                    <Tooltip title={countries.join(", ")}>
                                        <Tag>{__("%d countries", countries.length)}</Tag>
                                    </Tooltip>
                                );
                            } else {
                                value = __("Not defined");
                            }
                            break;
                        case "countryBypassType":
                            // only show when Country Bypass was active
                            if (!useOptions.isCountryBypass) {
                                return null;
                            }

                            label = __("Implicit consent for users from third countries");
                            value = value === "all" ? __("Accept all") : __("Accept only essentials");
                            break;
                        default:
                            known = false;
                            break;
                    }

                    return (
                        <Col key={key} md={12} sm={24}>
                            <div style={{ padding: "0 10px" }}>
                                {known ? <strong>{label}</strong> : <code>{label}</code>}: {value}
                            </div>
                        </Col>
                    );
                })}
            </Row>
        );
    },
);

export { ConsentTableRecordSettings };
