/**
 * Analytics Dashboard - Order statistics and charts
 */

import { __ } from '@wordpress/i18n';
import { useState, useCallback, useEffect } from '@wordpress/element';
import { SelectControl } from '@wordpress/components';
import { Icon, chartLine, money, shoppingCart } from '@wordpress/icons';
import { ordersApi } from '../../api/client';
import './AnalyticsDashboard.css';

export default function AnalyticsDashboard() {
    const [stats, setStats] = useState({
        totalOrders: 0,
        totalRevenue: 0,
        completedOrders: 0,
        pendingOrders: 0,
    });
    const [loading, setLoading] = useState(true);
    const [dateRange, setDateRange] = useState('30');

    const loadStats = useCallback(() => {
        setLoading(true);
        // This would be a dedicated stats API endpoint
        // For now, we'll fetch orders and calculate
        ordersApi.list({ limit: 1000 })
        .then(result => {
            if (result.data) {
                const orders = result.data.results || [];
                const totalRevenue = orders.reduce((sum, order) => {
                    if (order.status === 'completed') {
                        return sum + parseFloat(order.total || 0);
                    }
                    return sum;
                }, 0);

                setStats({
                    totalOrders: orders.length,
                    totalRevenue: totalRevenue,
                    completedOrders: orders.filter(o => o.status === 'completed').length,
                    pendingOrders: orders.filter(o => ['on-hold', 'payment-confirm', 'in-progress'].includes(o.status)).length,
                });
            }
        })
        .catch(error => {
            console.error('Load stats error:', error);
        })
        .finally(() => {
            setLoading(false);
        });
    }, [dateRange]);

    useEffect(() => {
        loadStats();
    }, [loadStats]);

    return (
        <div className="formipay-analytics-dashboard">
            <div className="formipay-dashboard-header">
                <h2>
                    <Icon icon={chartLine} />
                    { __('Dashboard', 'formipay') }
                </h2>
                <SelectControl
                    value={dateRange}
                    options={[
                        { value: '7', label: __('Last 7 days', 'formipay') },
                        { value: '30', label: __('Last 30 days', 'formipay') },
                        { value: '90', label: __('Last 90 days', 'formipay') },
                        { value: '365', label: __('Last year', 'formipay') },
                    ]}
                    onChange={setDateRange}
                />
            </div>

            {loading ? (
                <div className="formipay-loading">
                    <span className="spinner is-active" />
                </div>
            ) : (
                <>
                    <div className="formipay-stats-grid">
                        <div className="stat-card">
                            <div className="stat-icon">
                                <Icon icon={shoppingCart} size={24} />
                            </div>
                            <div className="stat-content">
                                <span className="stat-label">
                                    { __('Total Orders', 'formipay') }
                                </span>
                                <span className="stat-value">
                                    { stats.totalOrders }
                                </span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon">
                                <Icon icon={money} size={24} />
                            </div>
                            <div className="stat-content">
                                <span className="stat-label">
                                    { __('Total Revenue', 'formipay') }
                                </span>
                                <span className="stat-value">
                                    { stats.totalRevenue.toLocaleString('en-US', {
                                        style: 'currency',
                                        currency: 'USD',
                                    }) }
                                </span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon completed">
                                <span>✓</span>
                            </div>
                            <div className="stat-content">
                                <span className="stat-label">
                                    { __('Completed', 'formipay') }
                                </span>
                                <span className="stat-value">
                                    { stats.completedOrders }
                                </span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon pending">
                                <span>⏱</span>
                            </div>
                            <div className="stat-content">
                                <span className="stat-label">
                                    { __('Pending', 'formipay') }
                                </span>
                                <span className="stat-value">
                                    { stats.pendingOrders }
                                </span>
                            </div>
                        </div>
                    </div>

                    <div className="formipay-dashboard-charts">
                        <div className="chart-card">
                            <h3>
                                { __('Revenue Over Time', 'formipay') }
                            </h3>
                            <div className="chart-placeholder">
                                <p>
                                    { __('Chart placeholder - would use a library like Chart.js or Recharts', 'formipay') }
                                </p>
                            </div>
                        </div>

                        <div className="chart-card">
                            <h3>
                                { __('Orders by Status', 'formipay') }
                            </h3>
                            <div className="chart-placeholder">
                                <p>
                                    { __('Chart placeholder - would use a library like Chart.js or Recharts', 'formipay') }
                                </p>
                            </div>
                        </div>
                    </div>
                </>
            )}
        </div>
    );
}
