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

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

        // Render G2 chart
        useEffect(() => {
            if (ref.current) {
                const chart = new Chart({
                    container: ref.current,
                });

                const data =
                    main?.map(({ term_name, accepted, count }) => ({
                        term_name,
                        accepted:
                            accepted === "0"
                                ? __("Rejected")
                                : accepted === "1"
                                  ? __("Some services")
                                  : __("All services"),
                        count,
                    })) || [];

                chart.options({
                    type: "interval",
                    autoFit: true,
                    height: 300,
                    animate: false,
                    data,
                    encode: { x: "term_name", y: "count", color: "accepted" },
                    transform: [{ type: "stackY" }],
                    legend: {
                        color: { position: "right" },
                    },
                    scale: {
                        color: {
                            range: [colorScheme[2], colorScheme[3], "#e2e2e2"],
                        },
                    },
                    axis: {
                        y: {
                            title: {
                                visible: false,
                            },
                        },
                        x: {
                            title: "",
                        },
                    },
                    interaction: { elementHighlight: { background: true }, tooltip: { shared: true } },
                });

                /*chart
                    .axis("count", {
                        label: {
                            formatter: (text) => {
                                return text.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
                            },
                        },
                        title: {
                            offset: 70,
                            style: {
                                fill: "#aaaaaa",
                            },
                        },
                    })
                    .color("accepted", (accepted) => {
                        const { colorScheme } = getOtherOptionsFromWindow();
                        switch (accepted) {
                            case __("Rejected"):
                                return "#e2e2e2";
                            case __("Some services"):
                                return colorScheme[3];
                            case __("All services"):
                                return colorScheme[2];
                            default:
                                return "#FFFFFF";
                        }
                    });*/

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

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

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

export { StatsMainBarChart };
