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,
});

interface AnalyticsData {
    view: 'monthly' | 'yearly';
    year?: number;
    months?: Array<{
        month: number;
        monthName: string;
        income: number;
        expense: number;
        net: number;
    }>;
    years?: Array<{
        year: number;
        income: number;
        expense: number;
        net: number;
    }>;
    totalIncome: number;
    totalExpense: number;
    totalNet: number;
}

export default function IncomeOutcome()
{
    // get needed redux state
    const report = useAppSelector((state) => state.statisticsReducer.value.report)
    const currencySymbol = useAppSelector((state) => state.settingsReducer.value.appGeneralSettings.currencySymbol) ?? ''
    const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType)
    
    // declare global variables
    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
    
    // state for analytics data and view mode
    const [analyticsData, setAnalyticsData] = useState<AnalyticsData | null>(null);
    const [viewMode, setViewMode] = useState<'monthly' | 'yearly'>('monthly');
    const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
    const [loading, setLoading] = useState(true);
    
    // fetch analytics data
    useEffect(() => {
        const fetchAnalyticsData = async () => {
            try {
                setLoading(true);
                const response = await fetch(`/api/user/actions/income-expense-analytics?view=${viewMode}&year=${selectedYear}`);
                const result = await response.json();
                
                if (result.success) {
                    setAnalyticsData(result.data);
                }
            } catch (error) {
                console.error('Error fetching analytics data:', error);
            } finally {
                setLoading(false);
            }
        };
        
        fetchAnalyticsData();
    }, [viewMode, selectedYear]);
    
    // if loading show load screen
    if (loading || !analyticsData) {
        return (
            <div className="flex flex-col gap-5 [&_*]:dark:!text-text-dark p-5 w-full shadow border border-secondary-light bg-primary dark:bg-primary-dark rounded-[5px]">
                <h3 className="text-xl font-bold">{t('incomeOutcomeGeneralOverview')}</h3>
                <div className="flex justify-center items-center h-64">
                    <div className="text-lg">{t('loading')}</div>
                </div>
            </div>
        );
    }
    
    // prepare chart data based on view mode
    let data: number[] = [];
    let labels: string[] = [];
    let categories: string[] = [];
    
    if (viewMode === 'monthly' && analyticsData.months) {
        data = analyticsData.months.flatMap(month => [month.income, month.expense]);
        labels = [t('income'), t('outcome')];
        categories = analyticsData.months.flatMap(month => [month.monthName, month.monthName]);
    } else if (viewMode === 'yearly' && analyticsData.years) {
        data = analyticsData.years.flatMap(year => [year.income, year.expense]);
        labels = [t('income'), t('outcome')];
        categories = analyticsData.years.flatMap(year => [year.year.toString(), year.year.toString()]);
    }
    
    // prepare series data for grouped chart
    const incomeData = viewMode === 'monthly' 
        ? analyticsData.months?.map(month => month.income) || []
        : analyticsData.years?.map(year => year.income) || [];
    const expenseData = viewMode === 'monthly'
        ? analyticsData.months?.map(month => month.expense) || []
        : analyticsData.years?.map(year => year.expense) || [];
    const chartCategories = viewMode === 'monthly'
        ? analyticsData.months?.map(month => month.monthName) || []
        : analyticsData.years?.map(year => year.year.toString()) || [];
    // prepare chart options
    var options = {
        series: [
            {
                name: t('income'),
                data: incomeData,
                color: '#0263FF'
            },
            {
                name: t('outcome'),
                data: expenseData,
                color: '#E3342F'
            }
        ],
        chart: {
            height: 350,
            type: 'bar',
            toolbar: {
                show: true,
                tools: {
                    download: true,
                    selection: false,
                    zoom: false,
                    zoomin: false,
                    zoomout: false,
                    pan: false,
                    reset: false
                }
            }
        },
        plotOptions: {
            bar: {
                borderRadius: 4,
                columnWidth: '60%',
                dataLabels: {
                    position: 'top'
                }
            }
        },
        dataLabels: {
            enabled: true,
            formatter: function (val: number) {
                return currencySymbol + val.toLocaleString();
            },
            offsetY: -20,
            style: {
                fontSize: '12px',
                colors: [isDark ? '#fff' : '#000']
            }
        },
        legend: {
            position: 'top',
            horizontalAlign: 'right',
            fontSize: '14px',
            markers: {
                width: 10,
                height: 10,
                offsetX: isRtl ? 5 : -5,
            },
            itemMargin: {
                horizontal: 10,
                vertical: 5,
            },
        },
        colors: ['#0263FF', '#E3342F'],
        stroke: {
            width: 2,
            curve: 'straight',
        },
        grid: {
            borderColor: isDark ? '#333' : '#e0e0e0',
            strokeDashArray: 3,
        },
        xaxis: {
            categories: chartCategories,
            labels: {
                rotate: viewMode === 'monthly' ? -45 : 0,
                offsetX: isRtl ? 2 : 0,
                offsetY: 5,
                style: {
                    colors: isDark ? '#fff' : '#000',
                    fontSize: '12px',
                },
            },
            axisBorder: {
                color: isDark ? '#333' : '#e0e0e0'
            },
            axisTicks: {
                color: isDark ? '#333' : '#e0e0e0'
            }
        },
        yaxis: {
            labels: {
                offsetX: isRtl ? -10 : -10,
                offsetY: 0,
                style: {
                    colors: isDark ? '#fff' : '#000',
                    fontSize: '12px',
                },
                formatter: function (val: number) {
                    return currencySymbol + val.toLocaleString();
                }
            },
        },
        tooltip: {
            theme: isDark ? 'dark' : 'light',
            shared: true,
            intersect: false,
            y: {
                formatter: function (val: number) {
                    return currencySymbol + val.toLocaleString();
                }
            }
        },
    };
    // return the ui
    return (
        <>
            <div className="flex flex-col gap-5 [&_*]:dark:!text-text-dark p-5 w-full shadow border border-secondary-light bg-primary dark:bg-primary-dark rounded-[5px]">
                {/* Header with controls */}
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <h3 className="text-xl font-bold">{t('incomeOutcomeGeneralOverview')}</h3>
                    
                    <div className="flex flex-col sm:flex-row gap-3">
                        {/* View Mode Toggle */}
                        <div className="flex bg-secondary-light dark:bg-secondary-dark rounded-lg p-1">
                            <button
                                onClick={() => setViewMode('monthly')}
                                className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
                                    viewMode === 'monthly'
                                        ? 'bg-primary dark:bg-primary-dark text-text dark:text-text-dark shadow-sm'
                                        : 'text-text-secondary dark:text-text-secondary-dark hover:text-text dark:hover:text-text-dark'
                                }`}
                            >
                                {t('monthly')}
                            </button>
                            <button
                                onClick={() => setViewMode('yearly')}
                                className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
                                    viewMode === 'yearly'
                                        ? 'bg-primary dark:bg-primary-dark text-text dark:text-text-dark shadow-sm'
                                        : 'text-text-secondary dark:text-text-secondary-dark hover:text-text dark:hover:text-text-dark'
                                }`}
                            >
                                {t('yearly')}
                            </button>
                        </div>
                        
                        {/* Year Selector for Monthly View */}
                        {viewMode === 'monthly' && (
                            <select
                                value={selectedYear}
                                onChange={(e) => setSelectedYear(parseInt(e.target.value))}
                                className="px-3 py-1 rounded-md border border-secondary-light dark:border-secondary-dark bg-primary dark:bg-primary-dark text-text dark:text-text-dark text-sm"
                            >
                                {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map(year => (
                                    <option key={year} value={year}>{year}</option>
                                ))}
                            </select>
                        )}
                    </div>
                </div>
                
                {/* Summary Cards */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4">
                    <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
                        <div className="text-sm text-blue-600 dark:text-blue-400 font-medium">{t('totalIncome')}</div>
                        <div className="text-2xl font-bold text-blue-700 dark:text-blue-300">
                            {currencySymbol}{analyticsData.totalIncome.toLocaleString()}
                        </div>
                    </div>
                    <div className="bg-red-50 dark:bg-red-900/20 p-4 rounded-lg border border-red-200 dark:border-red-800">
                        <div className="text-sm text-red-600 dark:text-red-400 font-medium">{t('totalExpense')}</div>
                        <div className="text-2xl font-bold text-red-700 dark:text-red-300">
                            {currencySymbol}{analyticsData.totalExpense.toLocaleString()}
                        </div>
                    </div>
                    <div className={`p-4 rounded-lg border ${
                        analyticsData.totalNet >= 0 
                            ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                            : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
                    }`}>
                        <div className={`text-sm font-medium ${
                            analyticsData.totalNet >= 0
                                ? 'text-green-600 dark:text-green-400'
                                : 'text-red-600 dark:text-red-400'
                        }`}>{t('netProfit')}</div>
                        <div className={`text-2xl font-bold ${
                            analyticsData.totalNet >= 0
                                ? 'text-green-700 dark:text-green-300'
                                : 'text-red-700 dark:text-red-300'
                        }`}>
                            {currencySymbol}{analyticsData.totalNet.toLocaleString()}
                        </div>
                    </div>
                </div>
                
                {/* Chart */}
                <ReactApexChart series={options.series} options={options} type="bar" height={350} width={'100%'} />
            </div>
        </>
    )
}