import { useAppSelector } from '@/redux/store';
import { useTranslations } from 'next-intl';
import dynamic from 'next/dynamic';
import Cookies from 'universal-cookie';
import { useState, useEffect } from 'react';
const ReactApexChart = dynamic(() => import('react-apexcharts'), {
    ssr: false,
});

export default function ServicesSubscriptions()
{
    // get redux needed state
    const report = useAppSelector((state) => state.statisticsReducer.value.report);
    const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType);
    const [isClient, setIsClient] = useState(false);
    
    // declare global variables
    const cookies = new Cookies();
    const t = useTranslations('statistics');
    const locale = cookies.get("NEXT_LOCALE");
    const isRtl = locale === 'ar';
    const isDark = themeType === 'dark';
    
    // Set isClient to true after component mounts
    useEffect(() => {
        setIsClient(true);
    }, []);
    
    // if loading or no report, show loading spinner
    if (!report || !isClient) {
        return (
            <div className="w-full h-[350px] flex items-center justify-center">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900 dark:border-gray-100"></div>
            </div>
        );
    }

    // setup chart data with null checks
    const data = report?.servicesNameAndSubscribers?.value?.map((v: {
        _id: string;
        name: string;
        totalSubscribers: number;
    }) => v?.totalSubscribers) || [];
    
    // setup chart labels with null checks
    const labels = report?.servicesNameAndSubscribers?.value?.map((v: {
        _id: string;
        name: string;
        totalSubscribers: number;
    }) => v?.name) || [];
    
    // Return empty state if no data
    if (data.length === 0 || labels.length === 0) {
        return (
            <div className="w-full h-[350px] flex items-center justify-center">
                <p>{t('noDataAvailable')}</p>
            </div>
        );
    }
    
    // setup chart options
    const options = {
            series: [{
            name: t('subscription'),
            data: data
        }],
            annotations: {
            points: [{
            x: t('services'),
            seriesIndex: 0,
            label: {
                borderColor: '#775DD0',
                offsetY: 0,
                style: {
                    color: '#fff',
                    background: '#775DD0',
                },
            }
            }]
        },
        chart: {
            height: 350,
            type: 'bar',
        },
        plotOptions: {
            bar: {
                borderRadius: 10,
                columnWidth: '50%',         
                distributed: true,
            }
        },       
        fill: {
            type: isDark ? '' : 'gradient',
            gradient: isDark ? {} : {
                shadeIntensity: 1,
                inverseColors: !1,
                opacityFrom: isDark ? 0.19 : 0.28,
                opacityTo: 0.05,
                stops: isDark ? [100, 100] : [45, 100],
            },
        },    
        legend: {
            position: 'top',
            horizontalAlign: 'right',
            fontSize: '16px',
            markers: {
                width: 10,
                height: 10,
                offsetX: isRtl ? 5 : -5,
            },
            itemMargin: {
                horizontal: 10,
                vertical: 5,
            },
        },
        colors: ['#38C172', '#38C172' , '#E3342F' , '#0263FF', '#FF30F7'],
        dataLabels: {
            enabled: false
        },
        stroke: {
            width: 2,
            curve: 'straight',
        },
        grid: {
            row: {
                colors: [isDark ? '#333' : '#fff', '#f2f2f2'] // Adjust the grid row color for dark mode
            },
        },
        xaxis: {                
            labels: {
                rotate: -45,
                offsetX: isRtl ? 2 : 0,
                offsetY: 5,
                style: {
                    colors: isDark ? '#fff' : '#000',
                    fontSize: '12px',
                    cssClass: 'apexcharts-xaxis-title',
                },
            },
            categories: labels,
        },
        yaxis: {
            tickAmount: 7,
            labels: {
                offsetX: isRtl ? -30 : -10,
                offsetY: 0,
                style: {
                    colors: isDark ? '#fff' : '#000',
                    fontSize: '12px',
                    cssClass: 'apexcharts-yaxis-title',
                },
            },
        },
        tooltip: {
            theme: isDark ? 'dark' : 'light',
            x: {
                show: true,
            },
        },
    };
    // return the ui
    return (
        <>
            <div className="flex flex-col gap-5 [&_*]:dark:!text-text-dark p-5 lg:w-1/2 w-full shadow border border-secondary-light bg-primary dark:bg-primary-dark rounded-[5px]">
                <h3 className="text-xl font-bold">{t('sevicesGeneralOverview')}</h3>
                <ReactApexChart series={options.series} options={options} type="bar" height={350} width={'100%'} />
            </div>
        </>
    )
}