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

export default function MembersOverviewChart()
{
    // get needed redux state
    const report = useAppSelector((state) => state.statisticsReducer.value.report)
    const currentMembersGeneralOverviewDuration = useAppSelector((state) => state.statisticsReducer.value.currentMembersGeneralOverviewDuration)
    const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType)
    // declare global variables
    const dispatch = useAppDispatch()
    const cookies = new Cookies();
    const t = useTranslations('statistics');
    const locale = cookies.get("NEXT_LOCALE")
    const isRtl = locale == 'ar' ? true : false
    const isDark = themeType == 'dark' ? true : false
    const [chartSeries , setChartSeries] = useState<{}[]>([]);
    const [labels , setLabels] = useState<string[]>([])
    // revenue Chart
    // prepare chart series and handle the transaction between currentMembersGeneralOverviewDuration
    useEffect(() => {


        // Optional: Re-add a robust check for initial report data, if needed as a fallback.
        // For now, let's focus on debugging the data flow within the existing logic.
        if (!report || !report.membersGeneralOverview || !report.membersGeneralOverview.value) {
            //console.log("MembersOverviewChart - Report or general overview data is not available. Setting default.");
            setChartSeries([
                { name: t('totalMembers'), data: [0,0,0,0,0,0,0] },
                { name: t('totalActiveSubs'), data: [0,0,0,0,0,0,0] },
                { name: t('totalUnActiveSubs'), data: [0,0,0,0,0,0,0] },
                { name: t('totalMansMembers'), data: [0,0,0,0,0,0,0] },
                { name: t('totalGirlsMembers'), data: [0,0,0,0,0,0,0] },
            ]);
            setLabels([t('sat') , t('sun') , t('mon') , t('tue') , t('wed') , t('thu') , t('fri')]);
            return;
        }


        // if chart duration is set to this week
        if(currentMembersGeneralOverviewDuration == 'thisWeek')
        {
            // set the labels       
            const newLabelsThisWeek = [t('sat') , t('sun') , t('mon') , t('tue') , t('wed') , t('thu') , t('fri')];
            setLabels(newLabelsThisWeek);

            // init this weekdata
            let data_thisWeek = {
                'sat': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'sun': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'mon': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'tue': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'wed': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'thu': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                },
                'fri': {
                    'totalMembers': 0,
                    'totalActiveSubs': 0,
                    'totalUnActiveSubs': 0,
                    'totalMansMembers': 0,
                    'totalGirlsMembers': 0,
                }
            }
            // if there is a data from the backend we overwrite the currentData
            if(report.membersGeneralOverview.value.thisWeek?.days) {
                data_thisWeek = report.membersGeneralOverview.value.thisWeek.days;
            }


            // prepare the chart series
            const newChartSeriesThisWeek = [
                {
                    name: t('totalMembers'),
                    data: [
                        data_thisWeek['sat']?.['totalMembers'] || 0,
                        data_thisWeek['sun']?.['totalMembers'] || 0,
                        data_thisWeek['mon']?.['totalMembers'] || 0,
                        data_thisWeek['tue']?.['totalMembers'] || 0,
                        data_thisWeek['wed']?.['totalMembers'] || 0,
                        data_thisWeek['thu']?.['totalMembers'] || 0,
                        data_thisWeek['fri']?.['totalMembers'] || 0
                    ],
                },
                {
                    name: t('totalActiveSubs'),
                    data: [
                        data_thisWeek['sat']?.['totalActiveSubs'] || 0,
                        data_thisWeek['sun']?.['totalActiveSubs'] || 0,
                        data_thisWeek['mon']?.['totalActiveSubs'] || 0,
                        data_thisWeek['tue']?.['totalActiveSubs'] || 0,
                        data_thisWeek['wed']?.['totalActiveSubs'] || 0,
                        data_thisWeek['thu']?.['totalActiveSubs'] || 0,
                        data_thisWeek['fri']?.['totalActiveSubs'] || 0
                    ],
                },
                {
                    name: t('totalUnActiveSubs'),
                    data: [
                        data_thisWeek['sat']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['sun']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['mon']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['tue']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['wed']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['thu']?.['totalUnActiveSubs'] || 0,
                        data_thisWeek['fri']?.['totalUnActiveSubs'] || 0
                    ],
                },
                {
                    name: t('totalMansMembers'),
                    data: [
                        data_thisWeek['sat']?.['totalMansMembers'] || 0,
                        data_thisWeek['sun']?.['totalMansMembers'] || 0,
                        data_thisWeek['mon']?.['totalMansMembers'] || 0,
                        data_thisWeek['tue']?.['totalMansMembers'] || 0,
                        data_thisWeek['wed']?.['totalMansMembers'] || 0,
                        data_thisWeek['thu']?.['totalMansMembers'] || 0,
                        data_thisWeek['fri']?.['totalMansMembers'] || 0
                    ],
                },
                {
                    name: t('totalGirlsMembers'),
                    data: [
                        data_thisWeek['sat']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['sun']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['mon']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['tue']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['wed']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['thu']?.['totalGirlsMembers'] || 0,
                        data_thisWeek['fri']?.['totalGirlsMembers'] || 0
                    ],
                },
            ];

            setChartSeries(newChartSeriesThisWeek);
        }
        // if chart duration is set to this month
        else if(currentMembersGeneralOverviewDuration == 'thisMonth')
        {
            let thisMonthTotalSum : {
                week : number,
                thisWeekSum : {
                    "totalMembers": number,
                    "totalActiveSubs": number,
                    "totalUnActiveSubs": number,
                    "totalMansMembers": number,
                    "totalGirlsMembers": number
                }
            }[] = [];
            if(report.membersGeneralOverview.value.thisMonth)
            {
                // if we founded a data for the current month
                thisMonthTotalSum = (report.membersGeneralOverview.value.thisMonth.weeks || []).map((v : any , i : number) : {
                    week : number,
                    thisWeekSum : {
                        "totalMembers": number,
                        "totalActiveSubs": number,
                        "totalUnActiveSubs": number,
                        "totalMansMembers": number,
                        "totalGirlsMembers": number
                    }
                } => {
                    // we init the this week sum
                    let thisWeekSum = {
                            "totalMembers": 0,
                            "totalActiveSubs": 0,
                            "totalUnActiveSubs": 0,
                            "totalMansMembers": 0,
                            "totalGirlsMembers": 0
                        }
                    // we map through this month weeks
                    if (!v || !v.days) {
                        return {
                            week: v?.week || i,
                            thisWeekSum: thisWeekSum
                        };
                    }
                    // Since backend now provides cumulative totals, use the last day's values as the week total
                    if (v.days && v.days.length > 0) {
                        const lastDay = v.days[v.days.length - 1];
                        const dayKeys = ['fri', 'thu', 'wed', 'tue', 'mon', 'sun', 'sat'];
                        
                        // Find the last day with data
                        for (const dayKey of dayKeys) {
                            if (lastDay[dayKey] && Object.keys(lastDay[dayKey]).length > 0) {
                                thisWeekSum = {
                                    totalMembers: lastDay[dayKey]['totalMembers'] || 0,
                                    totalActiveSubs: lastDay[dayKey]['totalActiveSubs'] || 0,
                                    totalUnActiveSubs: lastDay[dayKey]['totalUnActiveSubs'] || 0,
                                    totalMansMembers: lastDay[dayKey]['totalMansMembers'] || 0,
                                    totalGirlsMembers: lastDay[dayKey]['totalGirlsMembers'] || 0,
                                };
                                break;
                            }
                        }
                    }
                    // each week we return there sum data
                    return {
                        week: v?.week || i,
                        thisWeekSum: thisWeekSum
                    }
                })
                const newLabelsThisMonth : string[] = [];
                thisMonthTotalSum.forEach(function(v , i) {
                    newLabelsThisMonth.push(t('week')+ ' ' +thisMonthTotalSum[i]["week"])
                })
                // set the labels       
                setLabels(newLabelsThisMonth)
                // we setup chart_series ( chart data )
                let newChartSeriesThisMonth : {
                    name: string,
                    data: number[]
                }[] = ['totalMembers' , 'totalActiveSubs' , 'totalUnActiveSubs' , 'totalMansMembers' , 'totalGirlsMembers'].map((v : string , i : number) : {
                    name: string,
                    data: number[]
                } => {
                    let data = thisMonthTotalSum.map((v2 : any) => {
                        let index : 'totalMembers' | 'totalActiveSubs' | 'totalUnActiveSubs' | 'totalMansMembers' | 'totalGirlsMembers' = v as any;
                        return v2?.thisWeekSum?.[index] || 0;
                    })
                    // return the line data
                    return {
                        name: t(v),
                        data: data
                    };
                })

                setChartSeries(newChartSeriesThisMonth)
            }
            // if there was no data we use default return
            else {
                setChartSeries([
                    { name: t('totalMembers'), data: [0,0,0,0] },
                    { name: t('totalActiveSubs'), data: [0,0,0,0] },
                    { name: t('totalUnActiveSubs'), data: [0,0,0,0] },
                    { name: t('totalMansMembers'), data: [0,0,0,0] },
                    { name: t('totalGirlsMembers'), data: [0,0,0,0] },
                ]);
                setLabels([t('week')+' 1', t('week')+' 2', t('week')+' 3', t('week')+' 4']);
            }

        }
        // if chart duration is set to this month
        else if(currentMembersGeneralOverviewDuration == 'thisYear')
        {
            // set the labels       
            const newLabelsThisYear = [t('1month'), t('2month'), t('3month'), t('4month'), t('5month'), t('6month'), t('7month'), t('8month'), t('9month'), t('10month'), t('11month'),t('12month') ];
            setLabels(newLabelsThisYear);

            // check if there is current month report
            let thisYearTotalSum : {
                month: number,
                thisMonthWeeksSum: {
                    "totalMembers": number,
                    "totalActiveSubs": number,
                    "totalUnActiveSubs": number,
                    "totalMansMembers": number,
                    "totalGirlsMembers": number
                }
            }[] = [];
            if(report?.membersGeneralOverview?.value?.thisYear)
            {
                // if we founded a data for the current month
                thisYearTotalSum = (report.membersGeneralOverview.value.thisYear.months || []).map((v : any , i : number) : {
                    month : number,
                    thisMonthWeeksSum : {
                        "totalMembers": number,
                        "totalActiveSubs": number,
                        "totalUnActiveSubs": number,
                        "totalMansMembers": number,
                        "totalGirlsMembers": number
                    }
                } => {
                    // Initialize thisMonthWeeksSum
                    let thisMonthWeeksSum = {
                        "totalMembers": 0,
                        "totalActiveSubs": 0,
                        "totalUnActiveSubs": 0,
                        "totalMansMembers": 0,
                        "totalGirlsMembers": 0
                    };

                    if (!v || !v.weeks) {
                        return {
                            month: v?.month !== undefined ? (v.month + 1) : (i + 1),
                            thisMonthWeeksSum: thisMonthWeeksSum
                        };
                    }

                    // Since backend now provides cumulative totals, use the last week's values as the month total
                    if (v.weeks && v.weeks.length > 0) {
                        const lastWeek = v.weeks[v.weeks.length - 1];
                        
                        if (lastWeek && lastWeek.days && lastWeek.days.length > 0) {
                            const lastDay = lastWeek.days[lastWeek.days.length - 1];
                            const dayKeys = ['fri', 'thu', 'wed', 'tue', 'mon', 'sun', 'sat'];
                            
                            // Find the last day with data in the last week
                            for (const dayKey of dayKeys) {
                                if (lastDay[dayKey] && Object.keys(lastDay[dayKey]).length > 0) {
                                    thisMonthWeeksSum = {
                                        totalMembers: lastDay[dayKey]['totalMembers'] || 0,
                                        totalActiveSubs: lastDay[dayKey]['totalActiveSubs'] || 0,
                                        totalUnActiveSubs: lastDay[dayKey]['totalUnActiveSubs'] || 0,
                                        totalMansMembers: lastDay[dayKey]['totalMansMembers'] || 0,
                                        totalGirlsMembers: lastDay[dayKey]['totalGirlsMembers'] || 0,
                                    };
                                    break;
                                }
                            }
                        }
                    }
                    return { month: v?.month !== undefined ? (v.month + 1) : (i + 1), thisMonthWeeksSum: thisMonthWeeksSum };
                });
                // prepare the labels - ensure correct month order from 1 to 12
                const newLabelsThisYear : string[] = [];
                for (let monthIndex = 1; monthIndex <= 12; monthIndex++) {
                    newLabelsThisYear.push(t(monthIndex + "month"));
                }
                setLabels(newLabelsThisYear)
                // we setup chart_series ( chart data )
                let newChartSeriesThisYear : {
                    name: string,
                    data: number[]
                }[] = ['totalMembers' , 'totalActiveSubs' , 'totalUnActiveSubs' , 'totalMansMembers' , 'totalGirlsMembers'].map((v : string , i : number) : {
                    name: string,
                    data: number[]
                } => {
                    let data = [];
                    // Ensure we have data for all 12 months in correct order
                    for (let monthIndex = 1; monthIndex <= 12; monthIndex++) {
                        const monthData = thisYearTotalSum.find(item => item.month === monthIndex);
                        let index : 'totalMembers' | 'totalActiveSubs' | 'totalUnActiveSubs' | 'totalMansMembers' | 'totalGirlsMembers' = v as any;
                        data.push(monthData?.thisMonthWeeksSum?.[index] || 0);
                    }
                    // return the line data
                    return {
                        name: t(v),
                        data: data
                    };
                })

                setChartSeries(newChartSeriesThisYear)
            }
            // if there was no data we use default return
            else {
                const defaultYearLabels = [t('1month'), t('2month'), t('3month'), t('4month'), t('5month'), t('6month'), t('7month'), t('8month'), t('9month'), t('10month'), t('11month'), t('12month')];
                setChartSeries([
                    { name: t('totalMembers'), data: [0,0,0,0,0,0,0,0,0,0,0,0] },
                    { name: t('totalActiveSubs'), data: [0,0,0,0,0,0,0,0,0,0,0,0] },
                    { name: t('totalUnActiveSubs'), data: [0,0,0,0,0,0,0,0,0,0,0,0] },
                    { name: t('totalMansMembers'), data: [0,0,0,0,0,0,0,0,0,0,0,0] },
                    { name: t('totalGirlsMembers'), data: [0,0,0,0,0,0,0,0,0,0,0,0] },
                ]);
                setLabels(defaultYearLabels);
            }

        }
    }, [report , currentMembersGeneralOverviewDuration , isRtl , isDark , t])
    // prepare the chart options
    const options : any = {
        series: chartSeries,
        options: {
            chart: {
                height: 325,
                type: 'area',
                fontFamily: 'Nunito, sans-serif',
                zoom: {
                    enabled: false,
                },
                toolbar: {
                    show: false,
                },
            },
            data_thisWeekLabels: {
                enabled: false,
            },
            stroke: {
                show: true,
                curve: 'smooth',
                width: 2,
                lineCap: 'square',
            },
            dropShadow: {
                enabled: true,
                opacity: 0.2,
                blur: 10,
                left: -7,
                top: 22,
            },
            colors: ['#38C172', '#38C172' , '#E3342F' , '#0263FF', '#FF30F7'],
            markers: {
                //discrete: [
                //    {
                //        seriesIndex: 0,
                //        data_thisWeekPointIndex: 1,
                //        fillColor: '#38C172',
                //        strokeColor: 'transparent',
                //        size: 7,
                //    },
                //    {
                //        seriesIndex: 1,
                //        data_thisWeekPointIndex: 1,
                //        fillColor: '#E3342F',
                //        strokeColor: 'transparent',
                //        size: 7,
                //    },
                //],
            },
            labels: labels,
            xaxis: {
                axisBorder: {
                    show: false,
                },
                axisTicks: {
                    show: false,
                },
                crosshairs: {
                    show: true,
                },
                labels: {
                    offsetX: isRtl ? 2 : 0,
                    offsetY: 5,
                    style: {
                        colors: isDark ? '#fff' : '#000',
                        fontSize: '12px',
                        cssClass: 'apexcharts-xaxis-title',
                    },
                },
            },
            yaxis: {
                tickAmount: 7,
                labels: {
                    formatter: (value: number) => {
                        if(value > 1000)
                        {
                            return parseInt(value.toFixed(0)) + t('k')
                        }
                        else {
                            return  parseInt(value.toFixed(0))
                        }
                    },
                    offsetX: isRtl ? -30 : -10,
                    offsetY: 0,
                    style: {
                        colors: isDark ? '#fff' : '#000',
                        fontSize: '12px',
                        cssClass: 'apexcharts-yaxis-title',
                    },
                },
            },
            grid: {
                borderColor: isDark ? '#191E3A' : '#E0E6ED',
                strokeDashArray: 5,
                xaxis: {
                    lines: {
                        show: false,
                    },
                },
                yaxis: {
                    lines: {
                        show: true,
                    },
                },
                padding: {
                    top: 0,
                    right: 0,
                    bottom: 0,
                    left: 0,
                },
            },
            legend: {
                position: 'top',
                horizontalAlign: 'right',
                fontSize: '16px',
                markers: {
                    width: 10,
                    height: 10,
                    offsetX: isRtl ? 5 : -5,
                },
                itemMargin: {
                    horizontal: 10,
                    vertical: 5,
                },
            },
            tooltip: {
                theme: isDark ? 'dark' : 'light',
                x: {
                    show: true,
                },
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    inverseColors: !1,
                    opacityFrom: isDark ? 0.19 : 0.28,
                    opacityTo: 0.05,
                    stops: isDark ? [100, 100] : [45, 100],
                },
            },
            responsive: [{
                breakpoint: 420,
                options: {
                    yaxis: {
                        show: false,
                        showAlways: false,
                    },
                    legend: {
                        offsetY: 10,
                        height: 60,
                        position: 'bottom',
                        horizontalAlign: 'center',
                        fontSize: '12px',
                        markers: {
                            width: 10,
                            height: 10,
                            offsetX: isRtl ? 5 : -5,
                        },
                        itemMargin: {
                            horizontal: 10,
                            vertical: 5,
                        },
                    },
                }
            }],
        },
    };
    // return the ui
    return (
        <>
            <div className="flex flex-col gap-5 [&_*]:dark:!text-text-dark p-5 lg:w-2/3 w-full shadow border border-secondary-light bg-primary dark:bg-primary-dark rounded-[5px]">
                <h3 className="text-xl font-bold">{t('membersGeneralOverview')}</h3>
                <div className="w-full flex gap-3 justify-end">
                    <button disabled={currentMembersGeneralOverviewDuration == 'thisWeek'} onClick={() => {
                        dispatch(setCurrentMembersGeneralOverviewDuration('thisWeek'))
                    }} className="disabled:dark:opacity-[0.5] disabled:opacity-[0.5]">
                        {t('thisWeek')}
                    </button>
                    <button disabled={currentMembersGeneralOverviewDuration == 'thisMonth'} onClick={() => {
                        dispatch(setCurrentMembersGeneralOverviewDuration('thisMonth'))
                    }} className="disabled:dark:opacity-[0.5] disabled:opacity-[0.5]">
                        {t('thisMonth')}
                    </button>
                    <button disabled={currentMembersGeneralOverviewDuration == 'thisYear'} onClick={() => {
                        dispatch(setCurrentMembersGeneralOverviewDuration('thisYear'))
                    }} className="disabled:dark:opacity-[0.5] disabled:opacity-[0.5]">
                        {t('thisYear')}
                    </button>
                </div>
                <ReactApexChart series={options.series} options={options.options} type="area" height={350} width={'100%'} />
            </div>
        </>
    )
}