import { SyncOutlined } from "@ant-design/icons";
import { App, Tooltip } from "antd";
import { observer } from "mobx-react";
import { useCallback, useState } from "react";

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

import type { FC } from "react";

const DashboardServiceCloudCardContent: FC = observer(() => {
    const { message } = App.useApp();
    const { cookieStore, optionStore } = useStores();
    const {
        busySettings,
        others: { isPro, isLicensed },
        cloudReleaseInfo: { blocker, service },
    } = optionStore;
    const [isSyncing, setIsSyncing] = useState(false);

    const handleSync = useCallback(async () => {
        if (isSyncing) {
            return;
        }

        setIsSyncing(true);
        try {
            await cookieStore.fetchTemplatesServices({ storage: "redownload" });
            await cookieStore.fetchTemplatesBlocker();
            await optionStore.fetchCurrentRevision();
            message.success("Template database successfully updated. You can see the latest templates now!");
        } catch (e) {
            message.error(e.responseJSON.message);
        } finally {
            setIsSyncing(false);
        }
    }, [isSyncing]);

    return (
        <>
            <p className="description">
                {__(
                    "Templates for hundreds of services that you could be running on your website must be downloaded from Real Cookie Banner's Service Cloud. The data will be downloaded locally to your server, so your website visitors will not need to connect to the cloud.",
                )}
            </p>
            {isLicensed ? (
                <>
                    {blocker ? (
                        <p className="description">
                            {_i(__("You have downloaded the service templates the last time on {{u/}}"), {
                                u: (
                                    <Tooltip
                                        title={
                                            <>
                                                <strong>{__("Services")}</strong>
                                                <br />
                                                {__("Release ID")}: {service?.releaseId}
                                                <br />
                                                {__("Pre-release")}:{" "}
                                                {service?.isPreReleaseEnabled ? __("Yes") : __("No")}
                                                <br />
                                                <strong>{__("Content Blocker")}</strong>
                                                <br />
                                                {__("Release ID")}: {blocker?.releaseId}
                                                <br />
                                                {__("Pre-release")}:{" "}
                                                {blocker?.isPreReleaseEnabled ? __("Yes") : __("No")}
                                            </>
                                        }
                                    >
                                        <u
                                            style={{
                                                textDecoration: "none",
                                                borderBottom: "1px dotted #000",
                                                cursor: "help",
                                            }}
                                        >
                                            {new Date(blocker.downloadTime).toLocaleString(
                                                document.documentElement.lang,
                                            )}
                                        </u>
                                    </Tooltip>
                                ),
                            })}
                        </p>
                    ) : busySettings ? null : (
                        <div className="notice notice-error inline below-h2 notice-alt" style={{ margin: "10px 0" }}>
                            <p className="description">
                                {__(
                                    'An error occurred when trying to download the templates from the Service Cloud for the first time. This means that the scanner will currently not be able to suggest scan results for service templates. The download will be performed again automatically in a few minutes, or click "Update templates" below.',
                                )}
                            </p>
                        </div>
                    )}
                    <p>
                        <Tooltip
                            title={__(
                                'The template database is downloaded to your WordPress and is updated daily. Click "Update templates" to download the latest version now!',
                            )}
                            placement="bottom"
                        >
                            <a
                                type="button"
                                className={`button ${isSyncing ? "button-disabled" : ""}`}
                                onClick={handleSync}
                            >
                                <SyncOutlined spin={isSyncing} />
                                &nbsp;
                                {__("Update templates")}
                            </a>
                        </Tooltip>
                    </p>
                </>
            ) : busySettings ? null : (
                <div className="notice notice-warning inline below-h2 notice-alt" style={{ margin: "10px 0" }}>
                    <p className="description">
                        {__(
                            "This functionality is only available with a valid license, as the service templates must be downloaded regularly from our cloud service.",
                        )}{" "}
                        &bull;{" "}
                        <a href={`#/licensing?navigateAfterActivation=${encodeURIComponent(window.location.href)}`}>
                            {isPro ? __("Activate license") : __("Activate free license")}
                        </a>
                    </p>
                </div>
            )}
        </>
    );
});

export { DashboardServiceCloudCardContent };
