import { Empty, Progress } from "antd";
import { useCallback, useState } from "react";

import { useI18n } from "../contexts/i18n.js";

function useTableBulkAction() {
    const { __ } = useI18n();
    const [currentProgress, setCurrentProgress] = useState<number>();
    const [currentSettings, setCurrentSettings] = useState<{
        total: number;
        title: string;
        abortController: AbortController;
    }>();

    const doBulkAction = useCallback(({ total, title }: { total: number; title: string }) => {
        let progress = 0;
        const abortController = new AbortController();

        let bulkDoneResolve: () => void;
        const bulkDonePromise = new Promise<void>((resolve) => (bulkDoneResolve = resolve));

        setCurrentProgress(0);
        setCurrentSettings({
            total,
            title,
            abortController,
        });

        return [
            () => {
                progress++;

                if (progress >= total) {
                    // We are done
                    setCurrentProgress(undefined);
                    setCurrentSettings(undefined);
                    bulkDoneResolve();
                } else {
                    setCurrentProgress(progress);
                }
            },
            abortController.signal,
            bulkDonePromise,
        ] as const;
    }, []);

    return [
        doBulkAction,
        typeof currentProgress === "number" && currentSettings ? (
            <Empty
                style={{ clear: "both" }}
                description={
                    <>
                        <div>{currentSettings.title}</div>
                    </>
                }
                image={
                    <Progress
                        type="circle"
                        width={100}
                        percent={+((currentProgress / currentSettings.total) * 100).toFixed(0)}
                        format={(percent) => (
                            <>
                                {percent} %<br />
                                <span style={{ fontSize: 10 }}>
                                    {currentProgress} / {currentSettings.total}
                                </span>
                            </>
                        )}
                    />
                }
            >
                <button
                    className="button button-primary"
                    onClick={() => {
                        currentSettings.abortController.abort();
                        setCurrentProgress(undefined);
                        setCurrentSettings(undefined);
                    }}
                >
                    {__("Cancel")}
                </button>
            </Empty>
        ) : undefined,
    ] as const;
}

export { useTableBulkAction };
