import { ClockCircleFilled } from "@ant-design/icons";
import { Badge, Tooltip } from "antd";

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

import { useStores } from "../../../store/stores.js";
import { DATABASE_CONSENT_MIGRATION_QUEUE_JOB } from "../../../types/queue.js";
import { __ } from "../../../utils/i18n.js";

import type { DatabaseConsentMigrationV2QueueJobData } from "../../../types/queue.js";
import type { FC, PropsWithChildren } from "react";

function calculatePercentForDatabaseConsentMigrationV2QueueJob({
    minId,
    maxId,
    process,
}: DatabaseConsentMigrationV2QueueJobData) {
    let total = 0;
    let done = 0;
    const diffMinMax = maxId - minId;

    if (diffMinMax <= 0) {
        return "n/a";
    }

    for (const migrationType of Object.values(process)) {
        for (const value of Object.values(migrationType)) {
            total += diffMinMax;
            done += (value > maxId ? maxId : value) - minId;
        }
    }

    return ((done / total) * 100).toLocaleString(document.documentElement.lang, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    });
}

const ConsentDbConsentMigrationV2Badge: FC<PropsWithChildren> = ({ children }) => {
    const {
        optionStore: {
            others: {
                colorScheme: [, , badgeColor],
            },
        },
    } = useStores();
    const { percent, currentJob, remaining } = useProgress<DatabaseConsentMigrationV2QueueJobData>({
        type: DATABASE_CONSENT_MIGRATION_QUEUE_JOB,
    });

    return remaining > 0 && percent > 0 && currentJob ? (
        <Tooltip
            title={__(
                "Real Cookie Banner v5.0 introduces an optimized database schema that allows consent documents to be stored in less storage space. Previously stored consent data is currently being automatically migrated in the background (%s %%). Please have a little patience!",
                calculatePercentForDatabaseConsentMigrationV2QueueJob(currentJob.data),
            )}
        >
            <Badge
                count={<ClockCircleFilled style={{ color: badgeColor }} />}
                style={{
                    top: -11,
                    height: 16,
                    lineHeight: "16px",
                }}
            >
                {children}
            </Badge>
        </Tooltip>
    ) : (
        children
    );
};

export { ConsentDbConsentMigrationV2Badge, calculatePercentForDatabaseConsentMigrationV2QueueJob };
