import { App } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";

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

import { useScannerProgress } from "./useScannerProgress.js";
import { crawlSitemap } from "../others/scanner/crawlSitemap.js";
import { useStores } from "../store/stores.js";
import { __ } from "../utils/i18n.js";

import type { ScanFromSitemapStep } from "../others/scanner/crawlSitemap.js";

type UseScannerProgressParameters = Parameters<typeof useScannerProgress>;

/**
 * Returns a callback which can be used within your button. It automatically
 * collects all scannable urls and posts it to the queue.
 */
function useScannerFromSitemap(
    fetchStatusInterval?: UseScannerProgressParameters[0],
    fetchAdditionalData?: UseScannerProgressParameters[1],
) {
    const { modal } = App.useApp();
    const [step, setStep] = useState<ScanFromSitemapStep>("idle");
    const { remaining, ...rest } = useScannerProgress(
        fetchStatusInterval,
        fetchAdditionalData,
        useCallback(() => {
            setStep("idle");
        }, []),
    );
    const { scannerStore, checklistStore } = useStores();

    const handleStart = useCallback(async () => {
        try {
            const sites = await crawlSitemap(setStep);

            setStep("add-to-queue");
            await scannerStore.addUrlsToQueue({
                urls: sites,
                purgeUnused: true,
            });
            await Promise.all([
                scannerStore.fetchResultExternals(),
                scannerStore.fetchResultTemplates(),
                refreshQueue(),
            ]);
            setStep("done");

            checklistStore.fetchChecklist();
        } catch (e) {
            if (e instanceof Error) {
                modal.error({
                    title: __("Whoops!"),
                    content: <span dangerouslySetInnerHTML={{ __html: e.message }} />,
                });
            }
            setStep("idle");
        }
    }, []);

    // Initially fetch status of the queue to get immediate status
    useEffect(() => {
        fetchStatus(true);
    }, []);

    const stepText = useMemo(() => {
        switch (step) {
            case "idle":
                return __("Scan complete website");
            case "find-sitemap":
                return __("Find your website sitemap...");
            case "collect-sitemap":
                return __("Collect all scannable URLs...");
            case "add-to-queue":
            case "done": // Pseudo-text, we are finished but our queue-status is not yet updated
                return __("Add URLs to queue...");
            default:
                break;
        }
        return "";
    }, [step]);

    return { handleStart, step, stepText, setStep, remaining, ...rest };
}

export { useScannerFromSitemap };
