import { CheckCircleTwoTone, CloseCircleTwoTone, QuestionCircleOutlined } from "@ant-design/icons";
import { Empty, Result, Table, Tag, Tooltip } from "antd";
import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";

import { ScannerMarkupPopover } from "./markup.js";
import { useScannerProgress } from "../../../../hooks/useScannerProgress.js";
import { useStores } from "../../../../store/stores.js";
import { __ } from "../../../../utils/i18n.js";

import type { ScannerResultExternalUrlSingle } from "../../../../models/scannerResultExternalUrlSingle.js";
import type { ScannerStore } from "../../../../store/scanner.js";
import type { CSSProperties, ComponentProps, FC } from "react";

const { Column } = Table;

const ScannerAllExternalUrlsTable: FC<{
    style?: CSSProperties;
    instance: Parameters<ScannerStore["fetchResultAllExternals"]>[0];
    reload?: boolean;
    reloadDependencies?: any[];
    tableProps?: ComponentProps<typeof Table<ScannerResultExternalUrlSingle>>;
}> = observer(({ instance, style, reloadDependencies = [], reload = true, tableProps = {} }) => {
    const { scannerStore } = useStores();
    const { identifier, busy } = instance;
    const urls = scannerStore.resultAllExternalUrls.get(identifier);
    const getRowKey = useCallback(({ data: { id } }: ScannerResultExternalUrlSingle) => id, []);
    const { remaining } = useScannerProgress();
    const [error, setError] = useState("");

    useEffect(() => {
        async function doAsync() {
            if (reload) {
                try {
                    await scannerStore.fetchResultAllExternals(instance);
                    setError("");
                } catch (e) {
                    setError((e as any).responseJSON?.message || (e as any).message);
                }
            }
        }

        doAsync();
    }, [instance, reload, ...reloadDependencies]);

    return (
        <>
            {remaining > 0 && (
                <div className="notice notice-info below-h2 notice-alt" style={{ margin: "0 0 10px" }}>
                    <p>{__("Since the scanner is currently still running, the table may be refreshed.")}</p>
                </div>
            )}
            <Table<ScannerResultExternalUrlSingle>
                locale={{
                    emptyText: error ? (
                        <Result title={__("Something went wrong.")} subTitle={error} status="500" />
                    ) : (
                        <Empty description={__("No external URL found")} />
                    ),
                }}
                dataSource={Array.from(urls ? urls.values() : [])}
                rowKey={getRowKey}
                size="small"
                bordered
                style={style}
                loading={!urls || urls.size === 0 ? busy : false}
                {...tableProps}
            >
                <Column<ScannerResultExternalUrlSingle>
                    title={__("Last scanned")}
                    defaultSortOrder="descend"
                    sorter={(a, b) => new Date(a.data.lastScanned).getTime() - new Date(b.data.lastScanned).getTime()}
                    dataIndex={["data", "lastScanned"]}
                    key="created"
                    render={(value, { data: { lastScanned } }) =>
                        new Date(lastScanned).toLocaleString(document.documentElement.lang)
                    }
                />
                <Column<ScannerResultExternalUrlSingle>
                    title={__("HTML Tag")}
                    dataIndex={["data", "tag"]}
                    key="tag"
                    render={(value, { data: { tag } }) => <Tag>{`<${tag} />`}</Tag>}
                />
                <Column<ScannerResultExternalUrlSingle>
                    title={
                        <Tooltip
                            title={__("This status shows you if the URL was blocked by a content blocker you defined.")}
                        >
                            <span>
                                {__("Blocked?")} <QuestionCircleOutlined style={{ color: "#9a9a9a" }} />
                            </span>
                        </Tooltip>
                    }
                    sorter={(a, b) => (a.data.blocked === b.data.blocked ? 0 : a.data.blocked ? -1 : 1)}
                    dataIndex={["data", "blocked"]}
                    key="blocked"
                    render={(value, { data: { blocked } }) =>
                        blocked ? (
                            <CheckCircleTwoTone twoToneColor="#52c41a" />
                        ) : (
                            <CloseCircleTwoTone twoToneColor="#eb2f96" />
                        )
                    }
                />
                <Column<ScannerResultExternalUrlSingle>
                    title={__("Blocked URL")}
                    dataIndex={["data", "blockedUrl"]}
                    key="blockedUrl"
                    render={(value, { blockedUrlTruncate, data: { blockedUrl } }) => (
                        <a href={blockedUrl} target="_blank" rel="noreferrer" title={blockedUrl}>
                            {blockedUrlTruncate}
                        </a>
                    )}
                />
                <Column<ScannerResultExternalUrlSingle>
                    title={__("Found on this URL")}
                    sorter={(a, b) => a.data.sourceUrl.localeCompare(b.data.sourceUrl)}
                    dataIndex={["data", "sourceUrl"]}
                    key="sourceUrl"
                    render={(value, { sourceUrlTruncate, data: { sourceUrl } }) => (
                        <a href={sourceUrl} target="_blank" rel="noreferrer">
                            {sourceUrlTruncate}
                        </a>
                    )}
                />
                <Column<ScannerResultExternalUrlSingle>
                    title={__("Actions")}
                    dataIndex={["data", "markup"]}
                    key="markup"
                    render={(value, record) => (record.data.markup ? <ScannerMarkupPopover record={record} /> : "")}
                />
            </Table>
        </>
    );
});

export { ScannerAllExternalUrlsTable };
