import { Chart } from "@antv/g2";
import { Empty, Spin } from "antd";
import { observer } from "mobx-react";
import { useEffect, useRef, useState } from "react";

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

import type { FC } from "react";

const StatsButtonClickedPieChart: FC = observer(() => {
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        const {
            statsStore,
            optionStore: {
                others: { colorScheme },
            },
        } = useStores();
        const {
            busyStats,
            filters: { dates, context },
            stats: { buttonsClicked },
        } = statsStore;
        const ref = useRef<HTMLDivElement>();
        const [showEmpty, setShowEmpty] = useState(false);

        useEffect(() => {
            statsStore.fetchButtonsClicked();
        }, [dates, context]);

        // Render G2 chart
        useEffect(() => {
            if (ref.current) {
                let data: Array<{
                    item: string;
                    count: number;
                    percent: number;
                }> = [];
                if (buttonsClicked) {
                    const {
                        none,
                        ind_all: indAll,
                        ind_custom: indCustom,
                        ind_essential: indEssential,
                        ind_close_icon: indCloseIcon,
                        main_all: mainAll,
                        main_custom: mainCustom,
                        main_essential: mainEssential,
                        main_close_icon: mainCloseIcon,
                        shortcode_revoke: shortcodeRevoke,
                        unblock,
                    } = buttonsClicked;
                    const total = Object.values(buttonsClicked)
                        .map(([, count]) => count)
                        .reduce((a, b) => a + b);

                    if (total) {
                        data = [
                            {
                                item: shortcodeRevoke[0],
                                count: shortcodeRevoke[1],
                                percent: shortcodeRevoke[1] / total,
                            },
                            { item: none[0], count: none[1], percent: none[1] / total },
                            { item: mainAll[0], count: mainAll[1], percent: mainAll[1] / total },
                            { item: mainEssential[0], count: mainEssential[1], percent: mainEssential[1] / total },
                            { item: mainCustom[0], count: mainCustom[1], percent: mainCustom[1] / total },
                            {
                                item: indAll[0],
                                count: indAll[1],
                                percent: indAll[1] / total,
                            },
                            {
                                item: indEssential[0],
                                count: indEssential[1],
                                percent: indEssential[1] / total,
                            },
                            {
                                item: indCloseIcon[0],
                                count: indCloseIcon[1],
                                percent: indCloseIcon[1] / total,
                            },
                            {
                                item: indCustom[0],
                                count: indCustom[1],
                                percent: indCustom[1] / total,
                            },
                            {
                                item: unblock[0],
                                count: unblock[1],
                                percent: unblock[1] / total,
                            },
                            {
                                item: mainCloseIcon[0],
                                count: mainCloseIcon[1],
                                percent: mainCloseIcon[1] / total,
                            },
                        ].filter(({ percent }) => percent > 0);
                    }
                }

                const chart = new Chart({
                    container: ref.current,
                });

                chart.options({
                    type: "interval",
                    autoFit: true,
                    height: 250,
                    animate: false,
                    data,
                    encode: { y: "percent", color: "item" },
                    transform: [{ type: "stackY" }],
                    coordinate: { type: "theta", outerRadius: 0.8 },
                    legend: {
                        color: { position: "bottom", layout: { justifyContent: "center" } },
                    },
                    scale: {
                        color: {
                            range: [
                                colorScheme[2],
                                colorScheme[3],
                                `${colorScheme[2]}e6`,
                                `${colorScheme[3]}e6`,
                                `${colorScheme[2]}d6`,
                                `${colorScheme[3]}d6`,
                                `${colorScheme[2]}b8`,
                                `${colorScheme[3]}b8`,
                                `${colorScheme[2]}8c`,
                                `${colorScheme[3]}8c`,
                            ],
                        },
                    },
                    style: {
                        stroke: "white",
                        inset: 1,
                        radius: 5,
                    },
                    labels: [
                        {
                            position: "spider",
                            transform: [{ type: "overlapDodgeY" }],
                            connectorDistance: 0,
                            text: (data) => `${data.item}: ${(data.percent * 100).toFixed(0)}%`,
                        },
                    ],
                    tooltip: {
                        items: [
                            (data) => ({
                                name: data.item,
                                value: data.count,
                            }),
                        ],
                    },
                });

                // Determine visibility
                chart.render();
                setShowEmpty(!data.length);

                return () => {
                    chart.destroy();
                };
            }
            return () => {
                // Silence is golden.
            };
        }, [ref, buttonsClicked, setShowEmpty]);

        return (
            <Spin spinning={busyStats.buttonClicked}>
                <div style={{ display: showEmpty ? "none" : undefined }} ref={ref}></div>
                {showEmpty && !busyStats.buttonClicked && (
                    <Empty description={__("No data available for this period.")} />
                )}
            </Spin>
        );
        /* onlypro:end */
    } else {
        return <div></div>;
    }
});

export { StatsButtonClickedPieChart };
