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

export default function IncomeOutcome()
{
    // get needed redux state
    const report = useAppSelector((state) => state.statisticsReducer.value.report);
    const settings = useAppSelector((state) => state.settingsReducer.value);
    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 or settings not loaded, show loading spinner
    if (!report || !isClient || !settings?.appGeneralSettings) {
        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>
        );
    }
    
    // Get currency symbol with fallback to '$' if not available
    const currencySymbol = settings.appGeneralSettings.currencySymbol || '$';
    
    // prepare chart data
    const data = [report?.totalIncome || 0, report?.totalOutcome || 0];
    // prepare chart labels
    const labels = [t('income'), t('outcome')];
    
    // prepare chart options
    const options = {
        series: [{
            name: currencySymbol,
            data: data
        }],
        annotations: {
            points: [{
                x: t('income'),
                seriesIndex: 0,
                label: {
                    borderColor: '#775DD0',
                    offsetY: 0,
                    style: {
                        color: '#fff',
                        background: '#775DD0',
                    },
                }
            }]
        },
        chart: {
            height: 350,
            type: 'bar',
            toolbar: {
                show: false
            }
        },
        plotOptions: {
            bar: {
                borderRadius: 10,
                columnWidth: '50%',            
                horizontal: true,            
                distributed: true,
            }
        },       
        legend: {
            position: 'top',
            horizontalAlign: 'right',
            fontSize: '16px',
            markers: {
                width: 10,
                height: 10,
                offsetX: isRtl ? 5 : -5,
            },
            itemMargin: {
                horizontal: 10,
                vertical: 5,
            },
            show: false
        },
        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],
            },
        },     
        colors: ['#0263FF', '#E3342F'],
        dataLabels: {
            enabled: false
        },
        stroke: {
            width: 2,
            curve: 'straight',
        },
        grid: {
            row: {
                colors: [isDark ? '#333' : '#fff', '#f2f2f2']
            },
        },
        xaxis: {                
            labels: {
                rotate: -45,
                offsetX: isRtl ? 2 : 0,
                offsetY: 5,
                style: {
                    colors: isDark ? '#fff' : '#000',
                },
                formatter: function(value: string) {
                    return value;
                }
            },
            categories: labels,
            axisBorder: {
                show: false
            },
            axisTicks: {
                show: false
            },
        },
        yaxis: {
            labels: {
                style: {
                    colors: isDark ? '#fff' : '#000',
                }
            }
        },
        tooltip: {
            theme: isDark ? 'dark' : 'light',
            y: {
                formatter: function(val: number) {
                    return `${currencySymbol} ${val}`;
                }
            }
        },
        responsive: [{
            breakpoint: 480,
            options: {
                legend: {
                    position: 'bottom',
                    offsetY: 10,
                    horizontalAlign: 'center',
                    fontSize: '12px',
                    markers: {
                        width: 10,
                        height: 10,
                        offsetX: isRtl ? 5 : -5,
                    },
                    itemMargin: {
                        horizontal: 10,
                        vertical: 5,
                    },
                },
            }
        }]
    };

    return (
        <div className="w-full h-auto p-5 shadow border border-secondary-light bg-primary dark:bg-primary-dark rounded-[5px]">
            <h3 className="text-xl font-bold mb-5">{t('incomeOutcomeGeneralOverview')}</h3>
            <div className="w-full h-[350px]">
                <ReactApexChart 
                    options={options} 
                    series={options.series} 
                    type="bar" 
                    height="100%" 
                    width="100%" 
                />
            </div>
        </div>
    );
}