import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import dynamic from 'next/dynamic';
import Cookies from 'universal-cookie';
import { useAppSelector } from '@/redux/store';

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

interface ServiceSubscriptionData {
    _id: string;
    name: string;
    status: string;
    activeSubscriptions: number;
    totalSubscriptions: number;
    expiredSubscriptions: number;
}

interface ServicesSubscriptionsResponse {
    services: ServiceSubscriptionData[];
    summary: {
        totalServices: number;
        activeServices: number;
        inactiveServices: number;
        totalActiveSubscriptions: number;
        totalExpiredSubscriptions: number;
        totalSubscriptions: number;
    };
}

export default function ServicesSubscriptions() {
    const [servicesData, setServicesData] = useState<ServicesSubscriptionsResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    
    // Get theme state from Redux
    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';
    const isDark = themeType === 'dark';
    
    // Fetch services subscriptions data
    useEffect(() => {
        const fetchServicesData = async () => {
            try {
                setLoading(true);
                const response = await fetch('/api/user/actions/services-subscriptions');
                const result = await response.json();
                
                if (result.success) {
                    setServicesData(result.data);
                    setError(null);
                } else {
                    setError(result.message || 'Failed to fetch data');
                }
            } catch (err) {
                setError('Network error occurred');
                console.error('Error fetching services data:', err);
            } finally {
                setLoading(false);
            }
        };
        
        fetchServicesData();
    }, []);
    
    // Show loading state
    if (loading) {
        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>
                <div className="flex items-center justify-center h-[350px]">
                    <div className="text-center">
                        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
                        <p>{t('loading')}</p>
                    </div>
                </div>
            </div>
        );
    }
    
    // Show error state
    if (error || !servicesData) {
        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>
                <div className="flex items-center justify-center h-[350px]">
                    <div className="text-center text-red-500">
                        <p>{error || 'No data available'}</p>
                    </div>
                </div>
            </div>
        );
    }
    
    // Prepare chart data
    const activeData = servicesData.services.map(service => service.activeSubscriptions);
    const expiredData = servicesData.services.map(service => service.expiredSubscriptions);
    const labels = servicesData.services.map(service => service.name);
    
    // Setup chart options
    const options = {
        series: [
            {
                name: t('activeSubscriptions'),
                data: activeData
            },
            {
                name: t('expiredSubscriptions'),
                data: expiredData
            }
        ],
        chart: {
            height: 350,
            type: 'bar' as const,
            stacked: true,
            toolbar: {
                show: true,
                tools: {
                    download: true,
                    selection: false,
                    zoom: false,
                    zoomin: false,
                    zoomout: false,
                    pan: false,
                    reset: false
                }
            }
        },
        plotOptions: {
            bar: {
                borderRadius: 8,
                columnWidth: '60%',
                horizontal: false,
            }
        },
        fill: {
            type: isDark ? 'solid' : 'gradient',
            gradient: isDark ? {} : {
                shadeIntensity: 1,
                inverseColors: false,
                opacityFrom: 0.85,
                opacityTo: 0.55,
                stops: [0, 100],
            },
        },
        legend: {
            position: 'top' as const,
            horizontalAlign: 'right' as const,
            fontSize: '14px',
            markers: {
                width: 12,
                height: 12,
                offsetX: isRtl ? 5 : -5,
            },
            itemMargin: {
                horizontal: 10,
                vertical: 5,
            },
            labels: {
                colors: isDark ? '#fff' : '#000',
            }
        },
        colors: ['#10B981', '#EF4444'], // Green for active, Red for expired
        dataLabels: {
            enabled: true,
            style: {
                colors: ['#fff']
            },
            formatter: function(val: number) {
                return val > 0 ? val.toString() : '';
            }
        },
        stroke: {
            width: 1,
            colors: ['transparent']
        },
        grid: {
            borderColor: isDark ? '#374151' : '#E5E7EB',
            strokeDashArray: 3,
        },
        xaxis: {
            categories: labels,
            labels: {
                rotate: -45,
                offsetX: isRtl ? 2 : 0,
                offsetY: 5,
                style: {
                    colors: isDark ? '#D1D5DB' : '#374151',
                    fontSize: '12px',
                },
                maxHeight: 80,
            },
            axisBorder: {
                color: isDark ? '#374151' : '#E5E7EB',
            },
            axisTicks: {
                color: isDark ? '#374151' : '#E5E7EB',
            }
        },
        yaxis: {
            labels: {
                offsetX: isRtl ? -10 : -5,
                style: {
                    colors: isDark ? '#D1D5DB' : '#374151',
                    fontSize: '12px',
                },
            },
            title: {
                text: t('subscriptionsCount'),
                style: {
                    color: isDark ? '#D1D5DB' : '#374151',
                    fontSize: '14px',
                    fontWeight: 600,
                }
            }
        },
        tooltip: {
            theme: isDark ? 'dark' : 'light',
            shared: true,
            intersect: false,
            y: {
                formatter: function(val: number, opts: any) {
                    const seriesName = opts.seriesIndex === 0 ? 
                         t('activeSubscriptions') : 
                         t('expiredSubscriptions');
                    return `${seriesName}: ${val}`;
                }
            }
        },
        responsive: [
            {
                breakpoint: 768,
                options: {
                    chart: {
                        height: 300
                    },
                    plotOptions: {
                        bar: {
                            columnWidth: '80%'
                        }
                    }
                }
            }
        ]
    };
    
    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]">
            {/* Header */}
            <div className="flex flex-col gap-2">
                <h3 className="text-xl font-bold">{t('sevicesGeneralOverview')}</h3>
                
                {/* Summary Stats */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                    <div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg">
                        <p className="text-blue-600 dark:text-blue-400 font-medium">
                             {t('totalServices')}
                         </p>
                        <p className="text-xl font-bold text-blue-700 dark:text-blue-300">
                            {servicesData.summary.totalServices}
                        </p>
                    </div>
                    
                    <div className="bg-green-50 dark:bg-green-900/20 p-3 rounded-lg">
                        <p className="text-green-600 dark:text-green-400 font-medium">
                             {t('activeSubscriptions')}
                         </p>
                        <p className="text-xl font-bold text-green-700 dark:text-green-300">
                            {servicesData.summary.totalActiveSubscriptions}
                        </p>
                    </div>
                    
                    <div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
                        <p className="text-red-600 dark:text-red-400 font-medium">
                             {t('expiredSubscriptions')}
                         </p>
                        <p className="text-xl font-bold text-red-700 dark:text-red-300">
                            {servicesData.summary.totalExpiredSubscriptions}
                        </p>
                    </div>
                    
                    <div className="bg-purple-50 dark:bg-purple-900/20 p-3 rounded-lg">
                        <p className="text-purple-600 dark:text-purple-400 font-medium">
                             {t('totalSubscriptions')}
                         </p>
                        <p className="text-xl font-bold text-purple-700 dark:text-purple-300">
                            {servicesData.summary.totalSubscriptions}
                        </p>
                    </div>
                </div>
            </div>
            
            {/* Chart */}
            <div className="w-full">
                {servicesData.services.length > 0 ? (
                    <ReactApexChart 
                        series={options.series} 
                        options={options} 
                        type="bar" 
                        height={350} 
                        width={'100%'} 
                    />
                ) : (
                    <div className="flex items-center justify-center h-[350px] text-gray-500 dark:text-gray-400">
                        <p>{t('noServicesFound')}</p>
                    </div>
                )}
            </div>
        </div>
    );
}