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

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

        // Render G2 chart
        useEffect(() => {
            if (ref.current && customBypass) {
                const total = Object.values(customBypass).reduce((pv, cv) => pv + cv, 0);
                const data = Object.keys(customBypass)
                    .map((customBypassType) => {
                        let item: string;
                        switch (customBypassType) {
                            case "none":
                                item = __("Consent by hand");
                                break;
                            case "dnt":
                                item = __('Consent by "Do Not Track"');
                                break;
                            default:
                                item = __(
                                    "Bypass by: %s",
                                    customBypassType.charAt(0).toUpperCase() + customBypassType.slice(1),
                                );
                                break;
                        }
                        const count = customBypass[customBypassType];
                        const percent = total > 0 ? count / total : 0;
                        return { item, count, percent };
                    })
                    .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, customBypass]);

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

export { StatsCustomBypassPieChart };
