import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import { IRootState } from '../../store';
import { getThemeChartColors, getThemeChartFont, isNeoScheme, isXpScheme } from '../../lib/theme-colors';
import dynamic from 'next/dynamic';

const ReactApexChart = dynamic(() => import('react-apexcharts'), {
    ssr: false,
});

const OrderStatusDashboard = () => {
    const [isMounted, setIsMounted] = useState(false);
    useEffect(() => {
        setIsMounted(true);
    }, []);

    const [orderStatusData, setOrderStatusData] = useState<number[]>([]);

    const fetchDataOrderStatus = async () => {
        const api_url = process.env.API_URL;
        const response = await fetch(`${api_url}api/dashboard/order-status`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
        });
        const res = await response.json();
        const valueArray: number[] = Object.keys(res).map((key) => res[key]);

        setOrderStatusData(valueArray);
    };

    useEffect(() => {
        if (isMounted) {
            fetchDataOrderStatus();
        }
    }, [isMounted]);

    const isDark = useSelector((state: IRootState) => state.themeConfig.theme === 'dark' || state.themeConfig.isDarkMode);
    const colorScheme = useSelector((state: IRootState) => state.themeConfig.colorScheme);
    const themeColors = getThemeChartColors(colorScheme);
    //Order Status
    const orderStatus: any = {
        series: orderStatusData,
        options: {
            chart: {
                type: 'donut',
                height: 460,
                fontFamily: getThemeChartFont(colorScheme),
            },
            dataLabels: {
                enabled: false,
            },
            colors: isNeoScheme(colorScheme)
                ? ['#e2a03f', themeColors[1], themeColors[0], themeColors[3], themeColors[4], themeColors[2]]
                : isXpScheme(colorScheme)
                ? themeColors
                : ['#e2a03f', '#2196F3', '#4361EE', '#00ab55', '#e7515a', '#888EA8'],
            legend: {
                position: 'bottom',
                horizontalAlign: 'center',
                fontSize: '14px',
                markers: {
                    width: 10,
                    height: 10,
                    offsetX: -2,
                },
                height: 50,
                offsetY: 20,
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '65%',
                        background: 'transparent',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                fontSize: '29px',
                                offsetY: -10,
                            },
                            value: {
                                show: true,
                                fontSize: '26px',
                                color: isDark ? '#bfc9d4' : undefined,
                                offsetY: 16,
                                formatter: (val: any) => {
                                    return val;
                                },
                            },
                            total: {
                                show: true,
                                label: 'Total',
                                color: '#888ea8',
                                fontSize: '29px',
                                formatter: (w: any) => {
                                    return w.globals.seriesTotals.reduce(function (a: any, b: any) {
                                        return a + b;
                                    }, 0);
                                },
                            },
                        },
                    },
                },
            },
            labels: ['Pending', 'Processing', 'In Delivery', 'Completed', 'Failed', 'Canceled'],
            states: {
                hover: {
                    filter: {
                        type: 'none',
                        value: 0.15,
                    },
                },
                active: {
                    filter: {
                        type: 'none',
                        value: 0.15,
                    },
                },
            },
        },
    };
    return (
        <>
            <div className="panel h-full">
                <div className="mb-5 flex items-center">
                    <h5 className="text-lg font-semibold dark:text-white-light">Order</h5>
                </div>
                <div>
                    <div className="rounded-lg bg-white dark:bg-black">
                        {isMounted ? (
                            <ReactApexChart series={orderStatus.series} options={orderStatus.options} type="donut" height={460} width={'100%'} />
                        ) : (
                            <div className="grid min-h-[325px] place-content-center bg-white-light/30 dark:bg-dark dark:bg-opacity-[0.08] ">
                                <span className="inline-flex h-5 w-5 animate-spin rounded-full  border-2 border-black !border-l-transparent dark:border-white"></span>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </>
    );
};
export default OrderStatusDashboard;
