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

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

import { __ } from "../../../../utils/i18n.js";
import { CodeMirror } from "../../../codemirror.js";

import type { ScannerResultExternalUrlSingle } from "../../../../models/scannerResultExternalUrlSingle.js";
import type { FC } from "react";

const ScannerMarkupPopover: FC<{ record: ScannerResultExternalUrlSingle }> = observer(({ record }) => {
    const { message } = App.useApp();
    const [open, setOpen] = useState(false);
    const {
        data: { id },
        markup,
        store,
    } = record;
    const cmSettings = useMemo(
        () =>
            markup
                ? {
                      ...(window as any).cm_settings,
                      codemirror: {
                          ...wp.codeEditor.defaultSettings.codemirror,
                          mode: markup.mime,
                          lint: false, // Disable linting as e.g. only starting-tags are captured without closing tag
                          readOnly: true,
                      },
                  }
                : {},
        [markup],
    );

    const toggleOpen = useCallback(() => {
        if (open) {
            setOpen(false);
        } else {
            setOpen(true);
            store.fetchMarkup(id);
        }
    }, [open]);

    const scanAgain = useCallback(async () => {
        store.addUrlsToQueue({
            urls: [record.data.sourceUrl],
            purgeUnused: false,
        });

        Promise.all([store.fetchResultExternals(), store.fetchResultTemplates(), refreshQueue()]);
        message.info(__("Page is scheduled for scanning again..."));
    }, []);

    return (
        <>
            <Modal
                title={__("Element found by markup")}
                open={open}
                width={700}
                bodyStyle={{ paddingBottom: 0 }}
                okButtonProps={{ style: { display: "none" } }}
                onCancel={toggleOpen}
                cancelText={__("Close")}
            >
                <Spin spinning={!markup}>{markup && <CodeMirror settings={cmSettings} value={markup.markup} />}</Spin>
            </Modal>
            <Dropdown.Button
                onClick={toggleOpen}
                menu={{
                    items: [
                        {
                            key: "scan-again",
                            onClick: scanAgain,
                            label: __("Scan again"),
                        },
                    ],
                }}
            >
                {__("Open markup")}
            </Dropdown.Button>
        </>
    );
});

export { ScannerMarkupPopover };
