import React, { useState, useEffect } from 'react';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    LineChart, Line, AreaChart, Area
} from 'recharts';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import InventoryIcon from '@mui/icons-material/Inventory';
import AnalyticsIcon from '@mui/icons-material/Analytics';
import WarningIcon from '@mui/icons-material/Warning';
import InfoIcon from '@mui/icons-material/Info';
import CloseIcon from '@mui/icons-material/Close';
import SearchIcon from '@mui/icons-material/Search';
import SortIcon from '@mui/icons-material/Sort';
import EditIcon from '@mui/icons-material/Edit';
import { getNonce, isPro } from '../../Helpers';
import { useModalManager } from '../../hooks/useModalManager';
import IncompleteOrdersSection from '../Components/Analytics/IncompleteOrdersSection';
import CartInteractionsAnalytics from '../Components/Analytics/CartInteractionsAnalytics';
import PriceModal from '../PriceModal/PriceModal';

import './wooanalytics.scss';

const WooAnalytics = ({ onVisitTab }) => {
    const { modalConfig, closeModal, showPremiumModal } = useModalManager();
    const [analyticsData, setAnalyticsData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [selectedPeriod, setSelectedPeriod] = useState('weekly');
    const [isWooCommerceActive, setIsWooCommerceActive] = useState(false);
    const [isAnalyticsEnabled, setIsAnalyticsEnabled] = useState(false);
    const [settingsLoading, setSettingsLoading] = useState(true);

    // Modal states
    const [modalOpen, setModalOpen] = useState(false);
    const [modalType, setModalType] = useState('');
    const [modalData, setModalData] = useState(null);

    // Top Products states
    const [searchTerm, setSearchTerm] = useState('');
    const [sortField, setSortField] = useState('total_revenue');
    const [sortDirection, setSortDirection] = useState('desc');
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage] = useState(10);

    // Handle glass effect interactions for mobile
    const handleGlassEffectTouch = (e) => {
        const container = e.currentTarget;
        const overlay = container.querySelector('.glass-overlay');

        if (overlay) {
            // Toggle glass overlay on mobile touch
            if (overlay.style.opacity === '1') {
                overlay.style.opacity = '0';
                overlay.style.visibility = 'hidden';
            } else {
                overlay.style.opacity = '1';
                overlay.style.visibility = 'visible';
            }
        }
    };

    // Handle navigation to WooCommerce settings tab
    const handleGoToSettings = () => {
        // Check if user has premium access
        /* if (!isPro()) {
            showPremiumModal();
            return;
        } */

        if (typeof onVisitTab === "function") {
            onVisitTab('woocommerce');
        } else {
            // Fallback to direct navigation if onVisitTab is not available
            window.location.href = 'admin.php?page=shop-explorer#/settings';
        }
    };

    // Fetch analytics data from real WooCommerce database
    const fetchAnalyticsData = () => {
        setLoading(true);
        wp.ajax.send('wpnts_woo_analytics_data', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                if (response.analytics_data && !response.analytics_data.error) {
                    setAnalyticsData(response.analytics_data);
                    setError(null);
                } else {
                    setError(response.analytics_data?.error || 'No analytics data available');
                }
                setLoading(false);
            },
            error(error) {
                console.error('Analytics fetch error:', error);
                setError('Failed to load analytics data');
                setLoading(false);
            },
        });
    };

    // Check WooCommerce status and analytics settings
    useEffect(() => {
        const checkInitialStatus = async () => {
            setSettingsLoading(true);

            try {
                // Check WooCommerce status
                const wooStatus = await new Promise((resolve, reject) => {
                    wp.ajax.send('nts_is_woocommerce_installed', {
                        data: { nonce: getNonce() },
                        success: resolve,
                        error: reject,
                    });
                });

                const isWooActive = wooStatus.status === 'active' ||
                    wooStatus.class_exists ||
                    wooStatus.plugin_active ||
                    wooStatus.functions_exist;
                setIsWooCommerceActive(isWooActive);

                if (!isWooActive) {
                    setSettingsLoading(false);
                    setLoading(false);
                    return;
                }

                // Check analytics settings
                try {
                    const settingsResponse = await new Promise((resolve, reject) => {
                        wp.ajax.send('notice_settings', {
                            data: { nonce: getNonce() },
                            success: resolve,
                            error: reject,
                        });
                    });

                    console.log('Settings response:', settingsResponse);
                    const wooSettings = settingsResponse.notice_settings?.wpnts_schedules_interval_woocommerce_settings;
                    const analyticsEnabled = wooSettings?.wooanalytics === true;

                    setIsAnalyticsEnabled(analyticsEnabled);
                    setSettingsLoading(false);

                    if (analyticsEnabled) {
                        fetchAnalyticsData();
                    } else {
                        setLoading(false);
                    }
                } catch (settingsError) {
                    console.warn('Settings check failed, assuming analytics disabled:', settingsError);
                    // If settings check fails, assume analytics is disabled but WooCommerce is active
                    setIsAnalyticsEnabled(false);
                    setSettingsLoading(false);
                    setLoading(false);
                }

            } catch (error) {

                // If WooCommerce check fails, assume it's not active
                setIsWooCommerceActive(false);
                setSettingsLoading(false);
                setLoading(false);
                setError('Failed to check WooCommerce status: ' + (error.message || 'Unknown error'));
            }
        };

        checkInitialStatus();
    }, []);

    useEffect(() => {
        if (isWooCommerceActive && isAnalyticsEnabled) {
            fetchAnalyticsData();
            // Refresh data every 5 minutes
            const interval = setInterval(fetchAnalyticsData, 300000);
            return () => clearInterval(interval);
        }
    }, [isWooCommerceActive, isAnalyticsEnabled]);

    // Show loading state
    if (settingsLoading || loading) {
        return (
            <div className="woo-analytics-container">
                <div className="analytics-loading">
                    <div className="loading-content">
                        <div className="loading-spinner">
                            <div className="spinner-ring"></div>
                            <div className="spinner-ring"></div>
                            <div className="spinner-ring"></div>
                        </div>
                        <h3>Loading Analytics</h3>
                        <p>Preparing your WooCommerce analytics dashboard...</p>
                        <div className="loading-steps">
                            <div className={`step ${!settingsLoading ? 'completed' : 'active'}`}>
                                <span className="step-number">1</span>
                                <span className="step-text">Checking system status</span>
                            </div>
                            <div className={`step ${!settingsLoading && !loading ? 'completed' : settingsLoading ? 'pending' : 'active'}`}>
                                <span className="step-number">2</span>
                                <span className="step-text">Loading analytics data</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Show analytics with glass effect when disabled
    if (!isAnalyticsEnabled && isWooCommerceActive) {
        return (
            <div className="woo-analytics-container">
                <div className="woo-analytics-dashboard analytics-preview-mode">
                    <div className="analytics-header">
                        <h1>
                            <AnalyticsIcon className="header-icon" />
                            WooCommerce Analytics Dashboard
                        </h1>
                        <div className="preview-badge">
                            Preview Mode - Enable to Access Full Features
                        </div>
                    </div>

                    {/* Order Analytics Overview with Glass Effect */}
                    <div className="analytics-section">
                        <h2>Order Analytics</h2>
                        <div className="analytics-grid">
                            <div className="analytics-card glass-effect-container" data-feature="order-analytics" onTouchStart={handleGlassEffectTouch}>
                                <div className="card-header">
                                    <ShoppingCartIcon className="card-icon" />
                                    <h3>Today's Orders</h3>
                                </div>
                                <div className="card-content">
                                    <div className="main-value">12</div>
                                    <div className="order-breakdown">
                                        <span className="status completed">✓ 8 Completed</span>
                                        <span className="status processing">⏳ 3 Processing</span>
                                        <span className="status pending">⏸ 1 Pending</span>
                                    </div>
                                </div>
                                <div className="glass-overlay">
                                    <div className="glass-content">
                                        <h4>Order Analytics</h4>
                                        <p>Track daily orders with real-time status breakdown. Monitor completed, processing, pending, and cancelled orders.</p>
                                        <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                    </div>
                                </div>
                            </div>

                            <div className="analytics-card glass-effect-container" data-feature="revenue-analytics" onTouchStart={handleGlassEffectTouch}>
                                <div className="card-header">
                                    <AttachMoneyIcon className="card-icon" />
                                    <h3>Today's Revenue</h3>
                                </div>
                                <div className="card-content">
                                    <div className="main-value">$2,450.00</div>
                                    <div className="sub-value">From completed & processing orders</div>
                                </div>
                                <div className="glass-overlay">
                                    <div className="glass-content">
                                        <h4>Revenue Analytics</h4>
                                        <p>Track daily, weekly, and monthly revenue with growth indicators and detailed breakdowns.</p>
                                        <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                    </div>
                                </div>
                            </div>

                            <div className="analytics-card glass-effect-container" data-feature="weekly-stats" onTouchStart={handleGlassEffectTouch}>
                                <div className="card-header">
                                    <TrendingUpIcon className="card-icon" />
                                    <h3>Last 7 Days</h3>
                                </div>
                                <div className="card-content">
                                    <div className="main-value">89 Orders</div>
                                    <div className="sub-value">$15,230.00 Revenue</div>
                                    <div className="order-breakdown">
                                        <span className="status completed">✓ 72</span>
                                        <span className="status processing">⏳ 12</span>
                                        <span className="status pending">⏸ 5</span>
                                    </div>
                                </div>
                                <div className="glass-overlay">
                                    <div className="glass-content">
                                        <h4>Weekly Performance</h4>
                                        <p>Comprehensive 7-day performance metrics including order volume and revenue trends.</p>
                                        <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                    </div>
                                </div>
                            </div>

                            <div className="analytics-card glass-effect-container" data-feature="monthly-stats" onTouchStart={handleGlassEffectTouch}>
                                <div className="card-header">
                                    <InventoryIcon className="card-icon" />
                                    <h3>Last 15 Days</h3>
                                </div>
                                <div className="card-content">
                                    <div className="main-value">156 Orders</div>
                                    <div className="sub-value">$28,940.00 Revenue</div>
                                    <div className="order-breakdown">
                                        <span className="status completed">✓ 134</span>
                                        <span className="status processing">⏳ 18</span>
                                        <span className="status refunded">↩ 4 Refunded</span>
                                    </div>
                                </div>
                                <div className="glass-overlay">
                                    <div className="glass-content">
                                        <h4>Extended Performance</h4>
                                        <p>15-day analytics showing extended trends, refunds, and comprehensive order status tracking.</p>
                                        <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Customer Analytics with Glass Effect */}
                    <div className="analytics-section">
                        <div className="section-header">
                            <h2>Customer Analytics</h2>
                        </div>
                        <div className="customer-analytics-grid glass-effect-container" data-feature="customer-analytics" onTouchStart={handleGlassEffectTouch}>
                            <div className="customer-card">
                                <h4>New Customers</h4>
                                <div className="customer-stats">
                                    <div className="stat">
                                        <span className="label">Today:</span>
                                        <span className="value">5</span>
                                    </div>
                                    <div className="stat">
                                        <span className="label">Last 7 days:</span>
                                        <span className="value">23</span>
                                    </div>
                                    <div className="stat">
                                        <span className="label">Last 15 days:</span>
                                        <span className="value">41</span>
                                    </div>
                                </div>
                            </div>

                            <div className="customer-card">
                                <h4>Returning Customers</h4>
                                <div className="customer-stats">
                                    <div className="stat">
                                        <span className="label">Today:</span>
                                        <span className="value">7</span>
                                    </div>
                                    <div className="stat">
                                        <span className="label">Last 7 days:</span>
                                        <span className="value">66</span>
                                    </div>
                                    <div className="stat">
                                        <span className="label">Last 15 days:</span>
                                        <span className="value">115</span>
                                    </div>
                                </div>
                            </div>
                            <div className="glass-overlay">
                                <div className="glass-content">
                                    <h4>Customer Analytics</h4>
                                    <p>Track new vs returning customers, customer acquisition patterns, and loyalty metrics.</p>
                                    <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Charts Section with Glass Effect */}
                    <div className="analytics-charts">
                        {/* Order Trends Chart */}
                        <div className="chart-container glass-effect-container" data-feature="order-trends" onTouchStart={handleGlassEffectTouch}>
                            <div className="chart-header">
                                <h3>Order Trends (Last 15 Days)</h3>
                            </div>
                            <div className="chart-content">
                                <div className="chart-placeholder">
                                    <div className="placeholder-chart">
                                        <div className="chart-bars">
                                            <div className="bar" style={{ height: '60%' }}></div>
                                            <div className="bar" style={{ height: '80%' }}></div>
                                            <div className="bar" style={{ height: '45%' }}></div>
                                            <div className="bar" style={{ height: '90%' }}></div>
                                            <div className="bar" style={{ height: '70%' }}></div>
                                            <div className="bar" style={{ height: '85%' }}></div>
                                            <div className="bar" style={{ height: '55%' }}></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="glass-overlay">
                                <div className="glass-content">
                                    <h4>Order Trends (Last 15 Days)</h4>
                                    <p>Interactive charts showing daily order patterns, revenue trends, and growth indicators over time.</p>
                                    <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                </div>
                            </div>
                        </div>

                        {/* Order Status Breakdown Chart */}
                        <div className="chart-container glass-effect-container" data-feature="order-status-breakdown" onTouchStart={handleGlassEffectTouch}>
                            <div className="chart-header">
                                <h3>Order Status Breakdown (Last 15 Days)</h3>
                            </div>
                            <div className="chart-content">
                                <div className="chart-placeholder">
                                    <div className="placeholder-chart">
                                        <div className="chart-bars stacked">
                                            <div className="bar-stack">
                                                <div className="bar-segment completed" style={{ height: '40%' }}></div>
                                                <div className="bar-segment processing" style={{ height: '20%' }}></div>
                                                <div className="bar-segment pending" style={{ height: '10%' }}></div>
                                            </div>
                                            <div className="bar-stack">
                                                <div className="bar-segment completed" style={{ height: '50%' }}></div>
                                                <div className="bar-segment processing" style={{ height: '25%' }}></div>
                                                <div className="bar-segment pending" style={{ height: '15%' }}></div>
                                            </div>
                                            <div className="bar-stack">
                                                <div className="bar-segment completed" style={{ height: '35%' }}></div>
                                                <div className="bar-segment processing" style={{ height: '15%' }}></div>
                                                <div className="bar-segment pending" style={{ height: '8%' }}></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="glass-overlay">
                                <div className="glass-content">
                                    <h4>Order Status Breakdown (Last 15 Days)</h4>
                                    <p>Stacked bar charts showing order status distribution with completed, processing, pending, and cancelled orders.</p>
                                    <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                </div>
                            </div>
                        </div>

                        {/* Top Products Chart */}
                        <div className="chart-container glass-effect-container" data-feature="top-products-chart" onTouchStart={handleGlassEffectTouch}>
                            <div className="chart-header">
                                <h3>Top Selling Products (Last 30 Days)</h3>
                            </div>
                            <div className="chart-content">
                                <div className="chart-placeholder">
                                    <div className="placeholder-chart horizontal">
                                        <div className="product-bar">
                                            <span className="product-name">Premium T-Shirt</span>
                                            <div className="bar" style={{ width: '90%' }}></div>
                                        </div>
                                        <div className="product-bar">
                                            <span className="product-name">Wireless Headphones</span>
                                            <div className="bar" style={{ width: '75%' }}></div>
                                        </div>
                                        <div className="product-bar">
                                            <span className="product-name">Coffee Mug</span>
                                            <div className="bar" style={{ width: '60%' }}></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="glass-overlay">
                                <div className="glass-content">
                                    <h4>Top Selling Products (Last 30 Days)</h4>
                                    <p>Bar charts showing best-selling products by quantity and revenue with detailed product performance metrics.</p>
                                    <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                </div>
                            </div>
                        </div>

                        {/* Revenue vs Orders Chart */}
                        <div className="chart-container glass-effect-container" data-feature="revenue-vs-orders" onTouchStart={handleGlassEffectTouch}>
                            <div className="chart-header">
                                <h3>Daily Revenue vs Orders</h3>
                            </div>
                            <div className="chart-content">
                                <div className="chart-placeholder">
                                    <div className="placeholder-chart line-chart">
                                        <div className="chart-lines">
                                            <svg width="100%" height="200" viewBox="0 0 300 200">
                                                <polyline points="0,150 50,120 100,100 150,80 200,90 250,70 300,60"
                                                    fill="none" stroke="#0073aa" strokeWidth="2" />
                                                <polyline points="0,180 50,160 100,140 150,120 200,130 250,110 300,100"
                                                    fill="none" stroke="#10b981" strokeWidth="2" />
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="glass-overlay">
                                <div className="glass-content">
                                    <h4>Daily Revenue vs Orders</h4>
                                    <p>Line charts correlating daily revenue with order volume to identify patterns and optimization opportunities.</p>
                                    <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Top Products Table with Glass Effect */}
                    <div className="top-products-table glass-effect-container" data-feature="top-products-table" onTouchStart={handleGlassEffectTouch}>
                        <div className="table-header">
                            <div className="table-title">
                                <h3>Top Products Details (Last 30 Days)</h3>
                            </div>
                            <div className="table-controls">
                                <div className="search-box">
                                    <SearchIcon className="search-icon" />
                                    <input type="text" placeholder="Search products..." disabled />
                                </div>
                            </div>
                        </div>

                        <div className="table-container">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Rank</th>
                                        <th>Product Name</th>
                                        <th>Quantity Sold</th>
                                        <th>Orders</th>
                                        <th>Avg Price</th>
                                        <th>Total Revenue</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td className="rank-cell"><span className="rank">#1</span></td>
                                        <td className="product-name">Premium T-Shirt</td>
                                        <td>156</td>
                                        <td>89</td>
                                        <td>$29.99</td>
                                        <td className="revenue-cell">$4,678.44</td>
                                        <td className="actions-cell">
                                            <button className="edit-product-btn" disabled>
                                                <EditIcon />
                                            </button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="rank-cell"><span className="rank">#2</span></td>
                                        <td className="product-name">Wireless Headphones</td>
                                        <td>78</td>
                                        <td>67</td>
                                        <td>$89.99</td>
                                        <td className="revenue-cell">$7,019.22</td>
                                        <td className="actions-cell">
                                            <button className="edit-product-btn" disabled>
                                                <EditIcon />
                                            </button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="rank-cell"><span className="rank">#3</span></td>
                                        <td className="product-name">Coffee Mug</td>
                                        <td>234</td>
                                        <td>156</td>
                                        <td>$12.99</td>
                                        <td className="revenue-cell">$3,039.66</td>
                                        <td className="actions-cell">
                                            <button className="edit-product-btn" disabled>
                                                <EditIcon />
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div className="glass-overlay">
                            <div className="glass-content">
                                <h4>Top Products Details (Last 30 Days)</h4>
                                <p>Detailed product performance table with search, sorting, and pagination. Track quantity sold, orders, pricing, and revenue.</p>
                                <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                            </div>
                        </div>
                    </div>

                    {/* Incomplete Orders Section with Glass Effect */}
                    <div className="incomplete-orders-section glass-effect-container" data-feature="incomplete-orders" onTouchStart={handleGlassEffectTouch}>
                        <div className="section-header">
                            <h2>
                                <ShoppingCartIcon className="section-icon" />
                                Incomplete Orders Analytics
                            </h2>
                            <div className="section-tabs">
                                <button className="tab-button active">Overview</button>
                                <button className="tab-button">Orders (15)</button>
                                <button className="tab-button">Most Abandoned</button>
                            </div>
                        </div>

                        <div className="incomplete-orders-overview">
                            <div className="stats-grid">
                                <div className="stat-card">
                                    <div className="stat-header">
                                        <ShoppingCartIcon className="stat-icon" />
                                        <h3>Total Incomplete</h3>
                                    </div>
                                    <div className="stat-value">15</div>
                                    <div className="stat-subtext">Orders not completed</div>
                                </div>

                                <div className="stat-card">
                                    <div className="stat-header">
                                        <AttachMoneyIcon className="stat-icon" />
                                        <h3>Recovery Potential</h3>
                                    </div>
                                    <div className="stat-value">$2,340.50</div>
                                    <div className="stat-subtext">Total abandoned value</div>
                                </div>

                                <div className="stat-card">
                                    <div className="stat-header">
                                        <TrendingUpIcon className="stat-icon" />
                                        <h3>Recovery Rate</h3>
                                    </div>
                                    <div className="stat-value">23%</div>
                                    <div className="stat-subtext">Orders eventually completed</div>
                                </div>

                                <div className="stat-card">
                                    <div className="stat-header">
                                        <WarningIcon className="stat-icon" />
                                        <h3>Today's Abandoned</h3>
                                    </div>
                                    <div className="stat-value">3</div>
                                    <div className="stat-subtext">New incomplete orders</div>
                                </div>
                            </div>

                            <div className="charts-grid">
                                <div className="chart-container">
                                    <div className="chart-header">
                                        <h3>Daily Abandonment Trends</h3>
                                    </div>
                                    <div className="chart-content">
                                        <div className="chart-placeholder">
                                            <div className="placeholder-chart line-chart">
                                                <svg width="100%" height="200" viewBox="0 0 300 200">
                                                    <polyline points="0,160 50,140 100,120 150,100 200,110 250,90 300,80"
                                                        fill="none" stroke="#ef4444" strokeWidth="2" />
                                                </svg>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="chart-container">
                                    <div className="chart-header">
                                        <h3>Most Abandoned Products</h3>
                                    </div>
                                    <div className="chart-content">
                                        <div className="chart-placeholder">
                                            <div className="placeholder-chart horizontal">
                                                <div className="product-bar">
                                                    <span className="product-name">Premium Jacket</span>
                                                    <div className="bar abandoned" style={{ width: '80%' }}></div>
                                                </div>
                                                <div className="product-bar">
                                                    <span className="product-name">Smart Watch</span>
                                                    <div className="bar abandoned" style={{ width: '65%' }}></div>
                                                </div>
                                                <div className="product-bar">
                                                    <span className="product-name">Running Shoes</span>
                                                    <div className="bar abandoned" style={{ width: '50%' }}></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="glass-overlay">
                            <div className="glass-content">
                                <h4>Incomplete Orders Analytics</h4>
                                <p>Track abandoned carts, recovery potential, and customer contact information. Includes daily trends and most abandoned products analysis.</p>
                                <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                            </div>
                        </div>
                    </div>

                    {/* Cart Interactions Analytics with Glass Effect */}
                    <div className="cart-interactions-analytics glass-effect-container" data-feature="cart-interactions" onTouchStart={handleGlassEffectTouch}>
                        <div className="analytics-header">
                            <h2>Cart Interactions Analytics</h2>
                            <p>Track how customers interact with products in their cart</p>
                        </div>

                        <div className="analytics-tabs">
                            <button className="tab-button active">Overview</button>
                            <button className="tab-button">Product Analysis</button>
                            <button className="tab-button">Daily Trends</button>
                        </div>

                        <div className="overview-tab">
                            <div className="insights-cards">
                                <div className="insight-card">
                                    <h3>Total Interactions</h3>
                                    <div className="insight-value">1,247</div>
                                    <p>Last 30 days</p>
                                </div>
                                <div className="insight-card">
                                    <h3>Removal Rate</h3>
                                    <div className="insight-value">18.5%</div>
                                    <p>Products removed from cart</p>
                                </div>
                                <div className="insight-card">
                                    <h3>Engagement Rate</h3>
                                    <div className="insight-value">34.2%</div>
                                    <p>Quantity adjustments</p>
                                </div>
                                <div className="insight-card">
                                    <h3>Most Removed</h3>
                                    <div className="insight-value-text">Premium Jacket</div>
                                    <p>Product with most removals</p>
                                </div>
                            </div>

                            <div className="charts-row">
                                <div className="chart-container">
                                    <h3>Interaction Types Distribution</h3>
                                    <div className="chart-placeholder">
                                        <div className="placeholder-pie-chart">
                                            <div className="pie-segment" style={{ background: 'conic-gradient(#4CAF50 0deg 144deg, #FF9800 144deg 216deg, #F44336 216deg 288deg, #2196F3 288deg 360deg)' }}></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="glass-overlay">
                            <div className="glass-content">
                                <h4>Cart Interactions Analytics</h4>
                                <p>Monitor customer cart behavior including product additions, removals, quantity changes, and interaction patterns.</p>
                                <div className="enable-hint">Enable WooCommerce Analytics to access live data</div>
                            </div>
                        </div>
                    </div>

                    {/* Activation Guide */}
                    <div className="activation-guide">
                        <div className="guide-content">
                            <h3>Enable Full Analytics Access</h3>
                            <p>To unlock all these powerful analytics features with live data:</p>
                            <div className="activation-steps">
                                <div className="step-item">
                                    <span className="step-number">1</span>
                                    <span>Go to <strong>Activity Guard → Configuration</strong></span>
                                </div>
                                <div className="step-item">
                                    <span className="step-number">2</span>
                                    <span>Navigate to <strong>WooCommerce</strong> tab</span>
                                </div>
                                <div className="step-item">
                                    <span className="step-number">3</span>
                                    <span>Enable <strong>"WooCommerce Analytics Dashboard"</strong></span>
                                </div>
                                <div className="step-item">
                                    <span className="step-number">4</span>
                                    <span>Save settings and return here</span>
                                </div>
                            </div>
                            {/* <button
                                onClick={handleGoToSettings}
                                className={`enable-analytics-btn ${!isPro() ? 'premium-disabled' : ''}`}
                                title={!isPro() ? 'Premium Feature - Upgrade to unlock' : 'Go to WooCommerce settings'}
                            >
                                Go to Settings {!isPro() ? '🔒' : ''}
                            </button> */}

                            <button
                                onClick={handleGoToSettings}
                                className={`enable-analytics-btn`}
                                title={'Go to WooCommerce settings'}
                            >
                                Go to Settings
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Show WooCommerce not active error
    if (!isWooCommerceActive) {
        return (
            <div className="woo-analytics-container">
                <div className="analytics-error">
                    <div className="error-content">
                        <WarningIcon className="error-icon" />
                        <h2>WooCommerce Required</h2>
                        <p>WooCommerce must be installed and activated to use the Analytics Dashboard.</p>
                        <div className="error-actions">
                            <a
                                href="plugin-install.php?s=woocommerce&tab=search&type=term"
                                className="install-woo-button"
                            >
                                Install WooCommerce
                            </a>
                            <button onClick={() => window.location.reload()} className="retry-button">
                                Refresh Page
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Show other errors
    if (error) {
        return (
            <div className="woo-analytics-container">
                <div className="analytics-error">
                    <div className="error-content">
                        <WarningIcon className="error-icon" />
                        <h2>Error Loading Analytics</h2>
                        <p>{error}</p>
                        <button onClick={fetchAnalyticsData} className="retry-button">
                            Retry
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    // Show no data message
    if (!analyticsData) {
        return (
            <div className="woo-analytics-container">
                <div className="analytics-no-data">
                    <div className="no-data-content">
                        <WarningIcon className="no-data-icon" />
                        <h3>No Analytics Data Available</h3>
                        <p>Make sure WooCommerce is active and you have some orders to display analytics.</p>
                        <button onClick={fetchAnalyticsData} className="retry-button">
                            Refresh Data
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    const {
        order_analytics = {},
        revenue_analytics = {},
        customer_analytics = {},
        top_products = [],
        order_trends = []
    } = analyticsData || {};

    // Show no data message if there's no meaningful data
    if (analyticsData && analyticsData.has_data === false) {
        return (
            <div className="woo-analytics-container">
                <div className="analytics-no-data">
                    <div className="no-data-content">
                        <AnalyticsIcon className="no-data-icon" />
                        <h3>No Sales Data Available</h3>
                        <p>Your WooCommerce store doesn't have any sales data yet. Once you start receiving orders, your analytics will appear here.</p>
                        <div className="no-data-suggestions">
                            <h4>Get started:</h4>
                            <ul>
                                <li>• Add products to your WooCommerce store</li>
                                <li>• Process some test orders</li>
                                <li>• Wait for customer purchases</li>
                                <li>• Check back here for analytics</li>
                            </ul>
                        </div>
                        <button onClick={fetchAnalyticsData} className="retry-button">
                            Refresh Data
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    // Format currency using WooCommerce currency
    const formatCurrency = (amount) => {
        let currency = revenue_analytics?.currency || '$';

        // Clean up HTML entities that might come from WooCommerce
        currency = currency.replace(/&nbsp;/g, ' ').replace(/&#\d+;/g, '');

        // If currency is still problematic, use a fallback
        if (currency.includes('&') || currency.length > 5) {
            currency = '$'; // Fallback to dollar sign
        }

        // Format the number with proper currency symbol
        const formatted = new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        }).format(amount || 0);

        return `${currency}${formatted}`;
    };

    // Format percentage
    const formatPercentage = (value) => {
        return `${value >= 0 ? '+' : ''}${value.toFixed(1)}%`;
    };

    // Modal handlers
    const openModal = (type, data = null) => {
        setModalType(type);
        setModalData(data);
        setModalOpen(true);
    };

    const closeAnalyticsModal = () => {
        setModalOpen(false);
        setModalType('');
        setModalData(null);
    };

    // Top Products filtering and sorting
    const getFilteredAndSortedProducts = () => {
        if (!top_products || !Array.isArray(top_products)) return [];

        let filtered = top_products.filter(product =>
            product.name && product.name.toLowerCase().includes(searchTerm.toLowerCase())
        );

        filtered.sort((a, b) => {
            let aVal = a[sortField] || 0;
            let bVal = b[sortField] || 0;

            if (sortField === 'name') {
                aVal = (a.name || '').toLowerCase();
                bVal = (b.name || '').toLowerCase();
                return sortDirection === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
            }

            return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
        });

        return filtered;
    };

    const getPaginatedProducts = () => {
        const filtered = getFilteredAndSortedProducts();
        const startIndex = (currentPage - 1) * itemsPerPage;
        return filtered.slice(startIndex, startIndex + itemsPerPage);
    };

    const getTotalPages = () => {
        return Math.ceil(getFilteredAndSortedProducts().length / itemsPerPage);
    };

    const handleSort = (field) => {
        if (sortField === field) {
            setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
        } else {
            setSortField(field);
            setSortDirection('desc');
        }
        setCurrentPage(1);
    };

    const openProductEditor = (productId) => {
        if (productId) {
            window.open(`post.php?post=${productId}&action=edit`, '_blank');
        }
    };

    return (
        <div className="woo-analytics-container">
            <div className="woo-analytics-dashboard">
                <div className="analytics-header">
                    <h1>
                        <AnalyticsIcon className="header-icon" />
                        WooCommerce Analytics Dashboard
                    </h1>
                    <div className="last-updated">
                        Last updated: {new Date(analyticsData.last_updated).toLocaleString()}
                    </div>
                </div>

                {/* Order Analytics Overview */}
                <div className="analytics-section">
                    <h2>Order Analytics</h2>
                    <div className="analytics-grid">
                        <div className="analytics-card">
                            <div className="card-header">
                                <ShoppingCartIcon className="card-icon" />
                                <h3>Today's Orders</h3>
                                <InfoIcon
                                    className="info-icon"
                                    onClick={() => openModal('todayOrders', order_analytics.today)}
                                />
                            </div>
                            <div className="card-content">
                                <div className="main-value">{order_analytics.today?.total || 0}</div>
                                <div className="order-breakdown">
                                    <span className="status completed">✓ {order_analytics.today?.completed || 0} Completed</span>
                                    <span className="status processing">⏳ {order_analytics.today?.processing || 0} Processing</span>
                                    <span className="status pending">⏸ {order_analytics.today?.pending || 0} Pending</span>
                                    <span className="status cancelled">✗ {order_analytics.today?.cancelled || 0} Cancelled</span>
                                    {(order_analytics.today?.refunded || 0) > 0 && (
                                        <span className="status refunded">↩ {order_analytics.today?.refunded || 0} Refunded</span>
                                    )}
                                    {(order_analytics.today?.on_hold || 0) > 0 && (
                                        <span className="status on-hold">⏸ {order_analytics.today?.on_hold || 0} On Hold</span>
                                    )}
                                </div>
                            </div>
                        </div>

                        <div className="analytics-card">
                            <div className="card-header">
                                <AttachMoneyIcon className="card-icon" />
                                <h3>Today's Revenue</h3>
                                <InfoIcon
                                    className="info-icon"
                                    onClick={() => openModal('todayRevenue', { revenue: revenue_analytics.today, orders: order_analytics.today })}
                                />
                            </div>
                            <div className="card-content">
                                <div className="main-value">{formatCurrency(revenue_analytics.today || 0)}</div>
                                <div className="sub-value">From completed & processing orders</div>
                            </div>
                        </div>

                        <div className="analytics-card">
                            <div className="card-header">
                                <TrendingUpIcon className="card-icon" />
                                <h3>Last 7 Days</h3>
                                <InfoIcon
                                    className="info-icon"
                                    onClick={() => openModal('weeklyStats', { revenue: revenue_analytics.week, orders: order_analytics.week })}
                                />
                            </div>
                            <div className="card-content">
                                <div className="main-value">{order_analytics.week?.total || 0} Orders</div>
                                <div className="sub-value">{formatCurrency(revenue_analytics.week || 0)} Revenue</div>
                                <div className="order-breakdown">
                                    <span className="status completed">✓ {order_analytics.week?.completed || 0}</span>
                                    <span className="status processing">⏳ {order_analytics.week?.processing || 0}</span>
                                    <span className="status pending">⏸ {order_analytics.week?.pending || 0}</span>
                                </div>
                            </div>
                        </div>

                        <div className="analytics-card">
                            <div className="card-header">
                                <InventoryIcon className="card-icon" />
                                <h3>Last 15 Days</h3>
                                <InfoIcon
                                    className="info-icon"
                                    onClick={() => openModal('fifteenDaysStats', { revenue: revenue_analytics.fifteen_days, orders: order_analytics.fifteen_days })}
                                />
                            </div>
                            <div className="card-content">
                                <div className="main-value">{order_analytics.fifteen_days?.total || 0} Orders</div>
                                <div className="sub-value">{formatCurrency(revenue_analytics.fifteen_days || 0)} Revenue</div>
                                <div className="order-breakdown">
                                    <span className="status completed">✓ {order_analytics.fifteen_days?.completed || 0}</span>
                                    <span className="status processing">⏳ {order_analytics.fifteen_days?.processing || 0}</span>
                                    <span className="status refunded">↩ {order_analytics.fifteen_days?.refunded || 0} Refunded</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Customer Analytics */}
                <div className="analytics-section">
                    <div className="section-header">
                        <h2>Customer Analytics</h2>
                        <InfoIcon
                            className="section-info-icon"
                            onClick={() => openModal('customerAnalytics', customer_analytics)}
                        />
                    </div>
                    <div className="customer-analytics-grid">
                        <div className="customer-card">
                            <h4>New Customers</h4>
                            <div className="customer-stats">
                                <div className="stat">
                                    <span className="label">Today:</span>
                                    <span className="value">{customer_analytics.new_customers_today || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="label">Last 7 days:</span>
                                    <span className="value">{customer_analytics.new_customers_week || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="label">Last 15 days:</span>
                                    <span className="value">{customer_analytics.new_customers_fifteen_days || 0}</span>
                                </div>
                            </div>
                        </div>

                        <div className="customer-card">
                            <h4>Returning Customers</h4>
                            <div className="customer-stats">
                                <div className="stat">
                                    <span className="label">Today:</span>
                                    <span className="value">{customer_analytics.returning_customers_today || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="label">Last 7 days:</span>
                                    <span className="value">{customer_analytics.returning_customers_week || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="label">Last 15 days:</span>
                                    <span className="value">{customer_analytics.returning_customers_fifteen_days || 0}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Charts Section */}
                <div className="analytics-charts">
                    {/* Order Trends Chart */}
                    <div className="chart-container">
                        <div className="chart-header">
                            <h3>Order Trends (Last 15 Days)</h3>
                            <InfoIcon
                                className="chart-info-icon"
                                onClick={() => openModal('orderTrends', order_trends)}
                            />
                        </div>
                        <div className="chart-content">
                            <ResponsiveContainer width="100%" height={300}>
                                <AreaChart data={order_trends}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="date" />
                                    <YAxis />
                                    <Tooltip
                                        formatter={(value, name) => [
                                            name === 'total_revenue' ? formatCurrency(value) : value,
                                            name === 'total_revenue' ? 'Revenue' :
                                                name === 'total_orders' ? 'Total Orders' :
                                                    name === 'completed' ? 'Completed' :
                                                        name === 'processing' ? 'Processing' :
                                                            name === 'pending' ? 'Pending' : name
                                        ]}
                                    />
                                    <Area
                                        type="monotone"
                                        dataKey="total_revenue"
                                        stroke="#0073aa"
                                        fill="#0073aa"
                                        fillOpacity={0.3}
                                    />
                                </AreaChart>
                            </ResponsiveContainer>
                        </div>
                    </div>

                    {/* Order Status Breakdown Chart */}
                    <div className="chart-container">
                        <div className="chart-header">
                            <h3>Order Status Breakdown (Last 15 Days)</h3>
                            <InfoIcon
                                className="chart-info-icon"
                                onClick={() => openModal('orderStatusBreakdown', order_trends)}
                            />
                        </div>
                        <div className="chart-content">
                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart data={order_trends}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="date" />
                                    <YAxis />
                                    <Tooltip />
                                    <Bar dataKey="completed" stackId="a" fill="#10b981" name="Completed" />
                                    <Bar dataKey="processing" stackId="a" fill="#3b82f6" name="Processing" />
                                    <Bar dataKey="pending" stackId="a" fill="#f59e0b" name="Pending" />
                                    <Bar dataKey="cancelled" stackId="a" fill="#ef4444" name="Cancelled" />
                                    <Bar dataKey="refunded" stackId="a" fill="#8b5cf6" name="Refunded" />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>

                    {/* Top Products Chart */}
                    <div className="chart-container">
                        <div className="chart-header">
                            <h3>Top Selling Products (Last 30 Days)</h3>
                            <InfoIcon
                                className="chart-info-icon"
                                onClick={() => openModal('topProductsChart', top_products)}
                            />
                        </div>
                        <div className="chart-content">
                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart data={top_products.slice(0, 8)}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis
                                        dataKey="name"
                                        angle={-45}
                                        textAnchor="end"
                                        height={80}
                                    />
                                    <YAxis />
                                    <Tooltip
                                        formatter={(value, name) => [
                                            name === 'total_revenue' ? formatCurrency(value) : value,
                                            name === 'total_quantity' ? 'Quantity Sold' :
                                                name === 'total_revenue' ? 'Revenue' : name
                                        ]}
                                    />
                                    <Bar dataKey="total_quantity" fill="#0073aa" name="Quantity" />
                                    <Bar dataKey="total_revenue" fill="#10b981" name="Revenue" />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>

                    {/* Revenue vs Orders Chart */}
                    <div className="chart-container">
                        <div className="chart-header">
                            <h3>Daily Revenue vs Orders</h3>
                            <InfoIcon
                                className="chart-info-icon"
                                onClick={() => openModal('revenueVsOrders', order_trends)}
                            />
                        </div>
                        <div className="chart-content">
                            <ResponsiveContainer width="100%" height={300}>
                                <LineChart data={order_trends}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="date" />
                                    <YAxis yAxisId="left" />
                                    <YAxis yAxisId="right" orientation="right" />
                                    <Tooltip
                                        formatter={(value, name) => [
                                            name === 'total_revenue' ? formatCurrency(value) : value,
                                            name === 'total_revenue' ? 'Revenue' : 'Orders'
                                        ]}
                                    />
                                    <Line
                                        yAxisId="left"
                                        type="monotone"
                                        dataKey="total_revenue"
                                        stroke="#0073aa"
                                        strokeWidth={2}
                                        name="Revenue"
                                    />
                                    <Line
                                        yAxisId="right"
                                        type="monotone"
                                        dataKey="total_orders"
                                        stroke="#10b981"
                                        strokeWidth={2}
                                        name="Orders"
                                    />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                </div>

                {/* Enhanced Top Products Table */}
                <div className="top-products-table">
                    <div className="table-header">
                        <div className="table-title">
                            <h3>Top Products Details (Last 30 Days)</h3>
                            <InfoIcon
                                className="table-info-icon"
                                onClick={() => openModal('topProductsTable', top_products)}
                            />
                        </div>

                        <div className="table-controls">
                            <div className="search-box">
                                <SearchIcon className="search-icon" />
                                <input
                                    type="text"
                                    placeholder="Search products..."
                                    value={searchTerm}
                                    onChange={(e) => {
                                        setSearchTerm(e.target.value);
                                        setCurrentPage(1);
                                    }}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>Rank</th>
                                    <th
                                        className={`sortable ${sortField === 'name' ? 'active' : ''}`}
                                        onClick={() => handleSort('name')}
                                    >
                                        Product Name
                                        <SortIcon className="sort-icon" />
                                    </th>
                                    <th
                                        className={`sortable ${sortField === 'total_quantity' ? 'active' : ''}`}
                                        onClick={() => handleSort('total_quantity')}
                                    >
                                        Quantity Sold
                                        <SortIcon className="sort-icon" />
                                    </th>
                                    <th
                                        className={`sortable ${sortField === 'order_count' ? 'active' : ''}`}
                                        onClick={() => handleSort('order_count')}
                                    >
                                        Orders
                                        <SortIcon className="sort-icon" />
                                    </th>
                                    <th
                                        className={`sortable ${sortField === 'avg_price' ? 'active' : ''}`}
                                        onClick={() => handleSort('avg_price')}
                                    >
                                        Avg Price
                                        <SortIcon className="sort-icon" />
                                    </th>
                                    <th
                                        className={`sortable ${sortField === 'total_revenue' ? 'active' : ''}`}
                                        onClick={() => handleSort('total_revenue')}
                                    >
                                        Total Revenue
                                        <SortIcon className="sort-icon" />
                                    </th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {getPaginatedProducts().length > 0 ? (
                                    getPaginatedProducts().map((product, index) => {
                                        const globalIndex = (currentPage - 1) * itemsPerPage + index + 1;
                                        return (
                                            <tr key={product.id || index}>
                                                <td className="rank-cell">
                                                    <span className="rank">#{globalIndex}</span>
                                                </td>
                                                <td className="product-name">
                                                    {product.name || 'Unknown Product'}
                                                </td>
                                                <td>{product.total_quantity || 0}</td>
                                                <td>{product.order_count || 0}</td>
                                                <td>{formatCurrency(product.avg_price || 0)}</td>
                                                <td className="revenue-cell">{formatCurrency(product.total_revenue || 0)}</td>
                                                <td className="actions-cell">
                                                    <button
                                                        className="edit-product-btn"
                                                        onClick={() => openProductEditor(product.id)}
                                                        title="Edit Product"
                                                    >
                                                        <EditIcon />
                                                    </button>
                                                </td>
                                            </tr>
                                        );
                                    })
                                ) : (
                                    <tr>
                                        <td colSpan="7" style={{ textAlign: 'center', padding: '20px' }}>
                                            {searchTerm ? 'No products found matching your search' : 'No product data available'}
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                    {/* Pagination */}
                    {getTotalPages() > 1 && (
                        <div className="pagination">
                            <div className="pagination-info">
                                Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, getFilteredAndSortedProducts().length)} of {getFilteredAndSortedProducts().length} products
                            </div>
                            <div className="pagination-controls">
                                <button
                                    className="pagination-btn"
                                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                                    disabled={currentPage === 1}
                                >
                                    Previous
                                </button>

                                {Array.from({ length: getTotalPages() }, (_, i) => i + 1).map(page => (
                                    <button
                                        key={page}
                                        className={`pagination-btn ${page === currentPage ? 'active' : ''}`}
                                        onClick={() => setCurrentPage(page)}
                                    >
                                        {page}
                                    </button>
                                ))}

                                <button
                                    className="pagination-btn"
                                    onClick={() => setCurrentPage(Math.min(getTotalPages(), currentPage + 1))}
                                    disabled={currentPage === getTotalPages()}
                                >
                                    Next
                                </button>
                            </div>
                        </div>
                    )}
                </div>

                {/* Incomplete Orders Section */}
                <IncompleteOrdersSection formatCurrency={formatCurrency} />

                {/* Cart Interactions Analytics */}
                <CartInteractionsAnalytics />

            </div>

            {/* Modal Component */}
            {modalOpen && (
                <div className="woo-analytics-modal-overlay" onClick={closeAnalyticsModal}>
                    <div className="woo-analytics-modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>{getModalTitle()}</h3>
                            <CloseIcon className="close-icon" onClick={closeAnalyticsModal} />
                        </div>
                        <div className="modal-content">
                            {renderModalContent()}
                        </div>
                    </div>
                </div>
            )}

            {/* Premium Modal */}
            <PriceModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position}
            />
        </div>
    );

    // Modal helper functions
    function getModalTitle() {
        switch (modalType) {
            case 'todayOrders': return "Today's Orders - Detailed Breakdown";
            case 'todayRevenue': return "Today's Revenue - Detailed Analysis";
            case 'weeklyStats': return "Last 7 Days - Performance Summary";
            case 'fifteenDaysStats': return "Last 15 Days - Performance Summary";
            case 'customerAnalytics': return "Customer Analytics - Detailed Insights";
            case 'orderTrends': return "Order Trends - Historical Data";
            case 'orderStatusBreakdown': return "Order Status Breakdown - Analysis";
            case 'topProductsChart': return "Top Products Chart - Performance Data";
            case 'revenueVsOrders': return "Revenue vs Orders - Correlation Analysis";
            case 'topProductsTable': return "Top Products - Complete Details";
            default: return "Analytics Details";
        }
    }

    function renderModalContent() {
        switch (modalType) {
            case 'todayOrders':
                return (
                    <div className="modal-stats">
                        <div className="stat-grid">
                            <div className="stat-item">
                                <span className="stat-label">Total Orders:</span>
                                <span className="stat-value">{modalData?.total || 0}</span>
                            </div>
                            <div className="stat-item completed">
                                <span className="stat-label">Completed:</span>
                                <span className="stat-value">{modalData?.completed || 0}</span>
                            </div>
                            <div className="stat-item processing">
                                <span className="stat-label">Processing:</span>
                                <span className="stat-value">{modalData?.processing || 0}</span>
                            </div>
                            <div className="stat-item pending">
                                <span className="stat-label">Pending:</span>
                                <span className="stat-value">{modalData?.pending || 0}</span>
                            </div>
                            <div className="stat-item cancelled">
                                <span className="stat-label">Cancelled:</span>
                                <span className="stat-value">{modalData?.cancelled || 0}</span>
                            </div>
                            {(modalData?.refunded || 0) > 0 && (
                                <div className="stat-item refunded">
                                    <span className="stat-label">Refunded:</span>
                                    <span className="stat-value">{modalData?.refunded || 0}</span>
                                </div>
                            )}
                            {(modalData?.on_hold || 0) > 0 && (
                                <div className="stat-item on-hold">
                                    <span className="stat-label">On Hold:</span>
                                    <span className="stat-value">{modalData?.on_hold || 0}</span>
                                </div>
                            )}
                        </div>
                        <div className="modal-description">
                            <p>This shows all orders placed today, broken down by their current status. Completed and processing orders contribute to revenue calculations.</p>
                        </div>
                    </div>
                );

            case 'todayRevenue':
                return (
                    <div className="modal-stats">
                        <div className="revenue-breakdown">
                            <div className="revenue-item">
                                <span className="revenue-label">Total Revenue Today:</span>
                                <span className="revenue-value">{formatCurrency(modalData?.revenue || 0)}</span>
                            </div>
                            <div className="revenue-sources">
                                <h4>Revenue Sources:</h4>
                                <div className="source-item">
                                    <span>Completed Orders ({modalData?.orders?.completed || 0}):</span>
                                    <span>Contributing to revenue</span>
                                </div>
                                <div className="source-item">
                                    <span>Processing Orders ({modalData?.orders?.processing || 0}):</span>
                                    <span>Contributing to revenue</span>
                                </div>
                            </div>
                        </div>
                        <div className="modal-description">
                            <p>Revenue includes only completed and processing orders. Pending, cancelled, and refunded orders are excluded from revenue calculations.</p>
                        </div>
                    </div>
                );

            case 'weeklyStats':
            case 'fifteenDaysStats':
                const period = modalType === 'weeklyStats' ? '7 days' : '15 days';
                return (
                    <div className="modal-stats">
                        <div className="period-summary">
                            <h4>Last {period} Summary:</h4>
                            <div className="summary-grid">
                                <div className="summary-item">
                                    <span className="summary-label">Total Orders:</span>
                                    <span className="summary-value">{modalData?.orders?.total || 0}</span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Total Revenue:</span>
                                    <span className="summary-value">{formatCurrency(modalData?.revenue || 0)}</span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Completed Orders:</span>
                                    <span className="summary-value">{modalData?.orders?.completed || 0}</span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Processing Orders:</span>
                                    <span className="summary-value">{modalData?.orders?.processing || 0}</span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Average Order Value:</span>
                                    <span className="summary-value">
                                        {modalData?.orders?.total > 0
                                            ? formatCurrency((modalData?.revenue || 0) / modalData.orders.total)
                                            : formatCurrency(0)
                                        }
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div className="modal-description">
                            <p>Performance metrics for the last {period}, showing order volume, revenue generation, and average order values.</p>
                        </div>
                    </div>
                );

            case 'customerAnalytics':
                return (
                    <div className="modal-stats">
                        <div className="customer-breakdown">
                            <h4>Customer Acquisition Analysis:</h4>
                            <div className="customer-grid">
                                <div className="customer-period">
                                    <h5>Today:</h5>
                                    <div className="customer-stats">
                                        <span>New: {modalData?.new_customers_today || 0}</span>
                                        <span>Returning: {modalData?.returning_customers_today || 0}</span>
                                    </div>
                                </div>
                                <div className="customer-period">
                                    <h5>Last 7 Days:</h5>
                                    <div className="customer-stats">
                                        <span>New: {modalData?.new_customers_week || 0}</span>
                                        <span>Returning: {modalData?.returning_customers_week || 0}</span>
                                    </div>
                                </div>
                                <div className="customer-period">
                                    <h5>Last 15 Days:</h5>
                                    <div className="customer-stats">
                                        <span>New: {modalData?.new_customers_fifteen_days || 0}</span>
                                        <span>Returning: {modalData?.returning_customers_fifteen_days || 0}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="modal-description">
                            <p>Customer analytics help you understand acquisition patterns and customer loyalty. New customers are first-time buyers, while returning customers have made previous purchases.</p>
                        </div>
                    </div>
                );

            case 'orderTrends':
            case 'orderStatusBreakdown':
                return (
                    <div className="modal-stats">
                        <div className="trends-summary">
                            <h4>Data Points: {modalData?.length || 0} days</h4>
                            <div className="trends-grid">
                                <div className="trend-item">
                                    <span className="trend-label">Total Revenue Period:</span>
                                    <span className="trend-value">
                                        {formatCurrency(
                                            modalData?.reduce((sum, day) => sum + (day.total_revenue || 0), 0) || 0
                                        )}
                                    </span>
                                </div>
                                <div className="trend-item">
                                    <span className="trend-label">Total Orders Period:</span>
                                    <span className="trend-value">
                                        {modalData?.reduce((sum, day) => sum + (day.total_orders || 0), 0) || 0}
                                    </span>
                                </div>
                                <div className="trend-item">
                                    <span className="trend-label">Peak Revenue Day:</span>
                                    <span className="trend-value">
                                        {modalData?.reduce((max, day) =>
                                            (day.total_revenue || 0) > (max.total_revenue || 0) ? day : max,
                                            modalData[0] || {}
                                        )?.date || 'N/A'}
                                    </span>
                                </div>
                                <div className="trend-item">
                                    <span className="trend-label">Peak Orders Day:</span>
                                    <span className="trend-value">
                                        {modalData?.reduce((max, day) =>
                                            (day.total_orders || 0) > (max.total_orders || 0) ? day : max,
                                            modalData[0] || {}
                                        )?.date || 'N/A'}
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div className="modal-description">
                            <p>Historical trend analysis showing daily performance patterns, peak periods, and overall growth trajectory over the selected timeframe.</p>
                        </div>
                    </div>
                );

            case 'revenueVsOrders':
                return (
                    <div className="modal-stats">
                        <div className="revenue-orders-summary">
                            <h4>Daily Revenue vs Orders Analysis:</h4>
                            <div className="revenue-orders-grid">
                                <div className="summary-item">
                                    <span className="summary-label">Total Days Analyzed:</span>
                                    <span className="summary-value">{modalData?.length || 0}</span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Total Revenue:</span>
                                    <span className="summary-value">
                                        {formatCurrency(
                                            modalData?.reduce((sum, day) => sum + (day.total_revenue || 0), 0) || 0
                                        )}
                                    </span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Total Orders:</span>
                                    <span className="summary-value">
                                        {modalData?.reduce((sum, day) => sum + (day.total_orders || 0), 0) || 0}
                                    </span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Average Order Value:</span>
                                    <span className="summary-value">
                                        {formatCurrency(
                                            modalData?.length > 0
                                                ? modalData.reduce((sum, day) => sum + (day.total_revenue || 0), 0) /
                                                Math.max(1, modalData.reduce((sum, day) => sum + (day.total_orders || 0), 0))
                                                : 0
                                        )}
                                    </span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Best Revenue Day:</span>
                                    <span className="summary-value">
                                        {modalData?.reduce((best, day) =>
                                            (day.total_revenue || 0) > (best.total_revenue || 0) ? day : best,
                                            modalData[0] || {}
                                        )?.date || 'N/A'}
                                    </span>
                                </div>
                                <div className="summary-item">
                                    <span className="summary-label">Most Orders Day:</span>
                                    <span className="summary-value">
                                        {modalData?.reduce((best, day) =>
                                            (day.total_orders || 0) > (best.total_orders || 0) ? day : best,
                                            modalData[0] || {}
                                        )?.date || 'N/A'}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Daily Breakdown Table */}
                        <div className="daily-breakdown-table">
                            <h4>Daily Performance Breakdown:</h4>
                            <div className="modal-table-container">
                                <table className="modal-daily-table">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Orders</th>
                                            <th>Revenue</th>
                                            <th>Avg Order Value</th>
                                            <th>Completed</th>
                                            <th>Processing</th>
                                            <th>Performance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {modalData && modalData.length > 0 ? (
                                            modalData.slice().reverse().map((day, index) => {
                                                const avgOrderValue = (day.total_orders || 0) > 0 ? (day.total_revenue || 0) / (day.total_orders || 0) : 0;
                                                const maxRevenue = Math.max(...modalData.map(d => d.total_revenue || 0));
                                                const revenuePercentage = maxRevenue > 0 ? ((day.total_revenue || 0) / maxRevenue * 100) : 0;
                                                return (
                                                    <tr key={index}>
                                                        <td className="date-cell">{day.date}</td>
                                                        <td className="orders-cell">{day.total_orders || 0}</td>
                                                        <td className="revenue-cell">
                                                            <strong>{formatCurrency(day.total_revenue || 0)}</strong>
                                                        </td>
                                                        <td className="avg-cell">{formatCurrency(avgOrderValue)}</td>
                                                        <td className="completed-cell">{day.completed || 0}</td>
                                                        <td className="processing-cell">{day.processing || 0}</td>
                                                        <td className="performance-cell">
                                                            <div className="performance-bar">
                                                                <div
                                                                    className="performance-fill"
                                                                    style={{ width: `${revenuePercentage}%` }}
                                                                ></div>
                                                                <span className="performance-text">
                                                                    {revenuePercentage.toFixed(0)}%
                                                                </span>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                );
                                            })
                                        ) : (
                                            <tr>
                                                <td colSpan="7" style={{ textAlign: 'center', padding: '20px' }}>
                                                    No daily data available
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div className="modal-description">
                            <p>Detailed daily breakdown showing the correlation between order volume and revenue generation. The performance bar shows each day's revenue relative to the best performing day.</p>
                        </div>
                    </div>
                );

            case 'topProductsChart':
            case 'topProductsTable':
                return (
                    <div className="modal-stats">
                        <div className="products-summary">
                            <h4>Product Performance Summary:</h4>
                            <div className="products-grid">
                                <div className="product-stat">
                                    <span className="product-label">Total Products:</span>
                                    <span className="product-value">{modalData?.length || 0}</span>
                                </div>
                                <div className="product-stat">
                                    <span className="product-label">Total Revenue:</span>
                                    <span className="product-value">
                                        {formatCurrency(
                                            modalData?.reduce((sum, product) => sum + (product.total_revenue || 0), 0) || 0
                                        )}
                                    </span>
                                </div>
                                <div className="product-stat">
                                    <span className="product-label">Total Quantity Sold:</span>
                                    <span className="product-value">
                                        {modalData?.reduce((sum, product) => sum + (product.total_quantity || 0), 0) || 0}
                                    </span>
                                </div>
                                <div className="product-stat">
                                    <span className="product-label">Top Performer:</span>
                                    <span className="product-value">
                                        {modalData?.[0]?.name || 'N/A'}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Detailed Products Table */}
                        <div className="products-detailed-table">
                            <h4>All Products Performance:</h4>
                            <div className="modal-table-container">
                                <table className="modal-products-table">
                                    <thead>
                                        <tr>
                                            <th>Rank</th>
                                            <th>Product Name</th>
                                            <th>Qty Sold</th>
                                            <th>Orders</th>
                                            <th>Avg Price</th>
                                            <th>Total Revenue</th>
                                            <th>Performance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {modalData && modalData.length > 0 ? (
                                            modalData.map((product, index) => {
                                                const totalRevenue = modalData.reduce((sum, p) => sum + (p.total_revenue || 0), 0);
                                                const revenuePercentage = totalRevenue > 0 ? ((product.total_revenue || 0) / totalRevenue * 100) : 0;
                                                return (
                                                    <tr key={product.id || index}>
                                                        <td className="rank-cell">
                                                            <span className={`rank ${index < 3 ? 'top-performer' : ''}`}>
                                                                #{index + 1}
                                                            </span>
                                                        </td>
                                                        <td className="product-name-cell">
                                                            <strong>{product.name || 'Unknown Product'}</strong>
                                                        </td>
                                                        <td className="quantity-cell">{product.total_quantity || 0}</td>
                                                        <td className="orders-cell">{product.order_count || 0}</td>
                                                        <td className="price-cell">{formatCurrency(product.avg_price || 0)}</td>
                                                        <td className="revenue-cell">
                                                            <strong>{formatCurrency(product.total_revenue || 0)}</strong>
                                                        </td>
                                                        <td className="performance-cell">
                                                            <div className="performance-bar">
                                                                <div
                                                                    className="performance-fill"
                                                                    style={{ width: `${revenuePercentage}%` }}
                                                                ></div>
                                                                <span className="performance-text">
                                                                    {revenuePercentage.toFixed(1)}%
                                                                </span>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                );
                                            })
                                        ) : (
                                            <tr>
                                                <td colSpan="7" style={{ textAlign: 'center', padding: '20px' }}>
                                                    No product data available
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div className="modal-description">
                            <p>Complete product performance analysis showing all products ranked by revenue generation over the last 30 days. The performance bar shows each product's contribution to total revenue.</p>
                        </div>
                    </div>
                );

            default:
                return <div>No additional details available.</div>;
        }
    }
};

export default WooAnalytics;