import { App, Modal } from "antd";
import { observer } from "mobx-react";
import { useCallback, useState } from "react";

import { refreshQueue } from "@devowl-wp/real-queue";

import { ScannerAllExternalUrlsTable } from "./allExternalUrls/table.js";
import { useStores } from "../../../store/stores.js";
import { __, _n } from "../../../utils/i18n.js";

import type { ScannerResultTemplate } from "../../../models/scannerResultTemplate.js";
import type { FC } from "react";

const ScannerTemplateCardActionOpenExternalUrlsTable: FC<{
    template: ScannerResultTemplate;
    onVisibleChange?: (state: boolean) => void;
}> = observer(({ template, onVisibleChange }) => {
    const { message } = App.useApp();
    const { scannerStore } = useStores();
    const allUrls = [];
    const {
        data: {
            identifier,
            name,
            consumerData: { scan },
        },
    } = template;
    const [expanded, setExpanded] = useState(false);

    const toggleExpandExternalUrls = useCallback(() => {
        onVisibleChange?.(!expanded);
        setExpanded(!expanded);
    }, [identifier, expanded]);

    const scanAllAgain = useCallback(async () => {
        const urls = scannerStore.resultAllExternalUrls.get(identifier);
        const arrayUrls = Array.from(urls ? urls.values() : []);

        for (const url of arrayUrls) {
            allUrls.push(url.data.sourceUrl);
        }

        await scannerStore.addUrlsToQueue({
            urls: allUrls,
            purgeUnused: false,
        });

        message.info(__("Pages are scheduled for scanning again..."));
        await Promise.all([scannerStore.fetchResultExternals(), scannerStore.fetchResultTemplates(), refreshQueue()]);
    }, []);

    // Live update all the URLs if the user has expanded the URL list
    const foundOnSitesCount = scan === false ? 0 : scan.foundOnSitesCount;

    return (
        <>
            <Modal
                title={name}
                open={expanded}
                width={1400}
                bodyStyle={{ paddingBottom: 0 }}
                onCancel={toggleExpandExternalUrls}
                cancelText={__("Close")}
                cancelButtonProps={{ style: { float: "right", marginLeft: "10px" } }}
                okButtonProps={{ type: "default" }}
                onOk={scanAllAgain}
                okText={__("Scan these pages again")}
            >
                <ScannerAllExternalUrlsTable
                    instance={template}
                    reload={expanded && foundOnSitesCount > 0}
                    reloadDependencies={[expanded, foundOnSitesCount]}
                />
            </Modal>
            <a
                onClick={(e) => {
                    e.preventDefault();
                    toggleExpandExternalUrls();
                }}
            >
                {_n("Embeds found on %d page", "Embeds found on %d pages", foundOnSitesCount, foundOnSitesCount)}
            </a>
        </>
    );
});

export { ScannerTemplateCardActionOpenExternalUrlsTable };
