import { CheckCircleTwoTone, IssuesCloseOutlined } from "@ant-design/icons";
import { Empty, Progress, Spin } from "antd";
import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";

import { useUpsellModal } from "@devowl-wp/react-cookie-banner-admin";

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

import type { FC } from "react";

const ScannerProgress: FC = observer(() => {
    const {
        optionStore: {
            others: { isPro },
        },
        scannerStore: { canShowResults, foundScanResultsCount, needsAttentionCount },
    } = useStores();
    const [statusCheckInterval, setStatusCheckInterval] = useState<number>(undefined);

    const {
        status,
        currentJob,
        total,
        percent,
        remaining,
        cancelling,
        handleStart: originalHandleStart,
        handleCancel,
        step,
        stepText,
    } = useScannerFromSitemap(statusCheckInterval, "rcb-scan-list");
    const disableScanButton = step !== "idle";

    const {
        isLicensed,
        modal: licenseActivationModal,
        open: openLicenseActivation,
    } = useUpsellModal({
        title: __("Scanner requires up-to-date search data from the Service Cloud"),
        description:
            __(
                "The scanner can automatically search your website for used services. To do this, it needs an up-to-date database of search data for services, which 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.",
            ) + (isPro ? "" : ` ${__("You can activate your free licence at any time, without any costs.")}`),
        mode: "license-activation",
        feature: "scanner",
        assetName: "service-cloud.svg",
        assetMaxHeight: 200,
    });

    const handleStart = useCallback(() => {
        if (isLicensed) {
            originalHandleStart();
        } else {
            openLicenseActivation();
        }
    }, [originalHandleStart, isLicensed, openLicenseActivation]);

    // Allow to force a template by query argument so the template center is disabled
    const { start } = useLocationQuery();

    useEffect(() => {
        if (start) {
            handleStart();
        }
    }, []);

    // Provide "live" refresh while scanning the complete website
    useEffect(() => {
        setStatusCheckInterval(remaining > 0 && currentJob && total ? 5000 : undefined);
    }, [remaining, currentJob, total]);

    return remaining === undefined ? (
        <Spin style={{ display: "block" }} />
    ) : (
        <div className="wp-clearfix">
            {licenseActivationModal}
            {canShowResults && (
                <div style={{ float: "left", margin: "5px 10px" }}>
                    {needsAttentionCount === 0 ? (
                        <>
                            <CheckCircleTwoTone twoToneColor="#52c41a" />
                            &nbsp;{__("All recommendations applied")}
                        </>
                    ) : (
                        <>
                            <IssuesCloseOutlined style={{ color: "#dba617" }} />
                            &nbsp;
                            {__(
                                "%d of %d recommendations applied",
                                foundScanResultsCount - needsAttentionCount,
                                foundScanResultsCount,
                            )}
                        </>
                    )}
                </div>
            )}
            {status === "failed" ? (
                <Empty
                    style={{ clear: "both" }}
                    description={__("Scan failed")}
                    image={<Progress type="circle" width={100} percent={100} status="exception" />}
                />
            ) : status === "done" ? (
                <Empty
                    style={{ clear: "both" }}
                    description={__("Scan completed")}
                    image={<Progress type="circle" width={100} percent={100} />}
                />
            ) : remaining > 0 && currentJob && total ? (
                <Empty
                    style={{ clear: "both" }}
                    description={
                        <>
                            <div>
                                {_i(
                                    __(
                                        "Currently scanning {{code}}%s{{/code}} (%d of %d pages scanned)...",
                                        currentJob.data.url,
                                        total - remaining,
                                        total,
                                    ),
                                    {
                                        code: <code />,
                                    },
                                )}
                            </div>
                            <div
                                className="notice notice-info inline below-h2 notice-alt"
                                style={{ margin: "10px 0 0 0", display: "inline-block" }}
                            >
                                <p>
                                    {__(
                                        "You can add already found services, edit your website or have a coffee in the meantime. The scanner runs in the background.",
                                    )}
                                </p>
                            </div>
                        </>
                    }
                    image={<Progress type="circle" width={100} percent={percent} />}
                >
                    <button className="button button-primary" onClick={handleCancel} disabled={cancelling}>
                        {__("Cancel scan")}
                    </button>
                </Empty>
            ) : canShowResults ? (
                <button
                    id="rcb-btn-scan-start"
                    className="button button-primary alignright"
                    onClick={handleStart}
                    disabled={disableScanButton}
                    style={{ marginBottom: 10, display: step !== "done" ? undefined : "none" }}
                >
                    {stepText}
                </button>
            ) : (
                <Empty
                    description={__(
                        "Scan your website for services that may set cookies or process personal data to obtain consent.",
                    )}
                >
                    <button className="button button-primary" onClick={handleStart} disabled={disableScanButton}>
                        {stepText}
                    </button>
                </Empty>
            )}
        </div>
    );
});

export { ScannerProgress };
