import { Button, List, Popconfirm, Spin, Tag } 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 { ScannerExternalUrlActionPopover } from "./externalUrlActionPopover.js";
import { useStores } from "../../../store/stores.js";
import { __, _n } from "../../../utils/i18n.js";

import type { ScannerResultExternalUrl } from "../../../models/scannerResultExternalUrl.js";
import type { FC } from "react";

const ScannerListItem: FC<{ item: ScannerResultExternalUrl }> = observer(({ item }) => {
    const [expanded, setExpanded] = useState(false);
    const {
        data: { host, foundOnSitesCount, tags, ignored },
        inactive,
        blockedStatus,
        blockedStatusText,
        busy,
    } = item;

    const { scannerStore } = useStores();

    const toggleExpandExternalUrls = useCallback(() => {
        setExpanded(!expanded);
    }, [host, expanded]);

    const scanAllAgain = useCallback(async () => {
        const allSourceUrls = [];
        try {
            await scannerStore.fetchResultAllExternals(item);

            scannerStore.resultAllExternalUrls.get(item.data.host).forEach((item) => {
                allSourceUrls.push(item.data.sourceUrl);
            });

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

            await Promise.all([scannerStore.fetchResultExternals(), refreshQueue()]);
        } catch (e) {
            if (e instanceof Error) {
                console.log(e);
            }
        }
    }, [item]);

    return (
        <>
            <List.Item
                itemID={host}
                actions={[
                    <ScannerExternalUrlActionPopover key="handle" item={item} />,
                    ignored && (
                        <a
                            onClick={() => {
                                item.ignore(false);
                                setExpanded(false);
                            }}
                        >
                            {__("Show recommendation again")}
                        </a>
                    ),
                    !inactive && (
                        <Popconfirm
                            key="delete"
                            title={__("Are you sure that you want to ignore this recommendation?")}
                            placement="bottomRight"
                            onConfirm={() => {
                                item.ignore(true);
                                setExpanded(false);
                            }}
                            okText={__("Ignore recommendation")}
                            cancelText={__("Cancel")}
                            overlayStyle={{ maxWidth: 350 }}
                        >
                            <a>{__("Ignore recommendation")}</a>
                        </Popconfirm>
                    ),
                ].filter(Boolean)}
                style={{ opacity: inactive && !expanded ? 0.6 : 1 }}
            >
                <Spin spinning={busy}>
                    <List.Item.Meta
                        title={
                            <span>
                                {host}{" "}
                                {tags.map((tag) => (
                                    <Tag key={tag}>{`<${tag} />`}</Tag>
                                ))}
                                {ignored && <Tag>{__("Ignored")}</Tag>}
                                {blockedStatus !== "none" && (
                                    <Tag color={blockedStatus === "partial" ? "warning" : "success"}>
                                        {blockedStatusText}
                                    </Tag>
                                )}
                            </span>
                        }
                        description={
                            <button className="button-link" onClick={toggleExpandExternalUrls}>
                                {expanded
                                    ? __("Close")
                                    : _n(
                                          "Embeds found on %d page",
                                          "Embeds found on %d pages",
                                          foundOnSitesCount,
                                          foundOnSitesCount,
                                      )}
                            </button>
                        }
                    />
                </Spin>
            </List.Item>
            {expanded && (
                <ScannerAllExternalUrlsTable
                    instance={item}
                    reload={expanded && foundOnSitesCount > 0}
                    reloadDependencies={[expanded, foundOnSitesCount]}
                    style={{ marginTop: "-6px" }}
                    tableProps={{
                        footer: () => (
                            <div style={{ textAlign: "right" }}>
                                <Button onClick={scanAllAgain}>{__("Scan these pages again")}</Button>
                            </div>
                        ),
                    }}
                />
            )}
        </>
    );
});

export { ScannerListItem };
