import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../utils/api';
import { useToast } from '../App';
import LoadingState from '../components/LoadingState';

const Dashboard = () => {
    const navigate = useNavigate();
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(true);
    const [stats, setStats] = useState({
        orders: { total: 0, pending: 0, processing: 0, completed: 0, revenue: 0, growth: 0 },
        products: { total: 0, in_stock: 0, out_of_stock: 0, low_stock: 0 },
        vendors: { total: 0, active: 0, pending: 0 },
        sync: { last_sync: null, status: 'idle', pending_operations: 0 }
    });
    const [modes, setModes] = useState({
        databaseMode: true,
        googleSheetsMode: false,
        multivendorMode: false
    });
    const [recentActivity, setRecentActivity] = useState([]);
    const [syncStatus, setSyncStatus] = useState({
        isRunning: false,
        lastSync: null,
        pendingOperations: 0
    });
    const [userInfo, setUserInfo] = useState(null);
    const [frontendSettings, setFrontendSettings] = useState(null);

    const isFrontend = !window.location.pathname.includes('wp-admin');

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

    const loadDashboardData = async () => {
        try {
            setLoading(true);

            // Get user info from shopExplorerData
            const currentUser = window.shopExplorerData?.currentUser;
            if (currentUser) {
                setUserInfo({
                    display_name: currentUser.name,
                    email: currentUser.email,
                    roles: currentUser.roles
                });
            }

            // Load all dashboard data in parallel
            const [statsResponse, activityResponse, syncResponse] = await Promise.allSettled([
                api.getDashboardStats(),
                api.getRecentActivity(),
                api.getSyncStatus()
            ]);

            // Handle stats
            if (statsResponse.status === 'fulfilled' && statsResponse.value.success) {
                setStats(statsResponse.value.stats);
            }

            // Handle recent activity
            if (activityResponse.status === 'fulfilled' && activityResponse.value.success) {
                setRecentActivity(activityResponse.value.activity || []);
            }

            // Handle sync status
            if (syncResponse.status === 'fulfilled' && syncResponse.value.success) {
                setSyncStatus(syncResponse.value.status || {});
            }

            // Load configuration
            try {
                const configResponse = await api.getConfiguration();
                if (configResponse.success) {
                    setModes({
                        databaseMode: configResponse.config.database_mode_enabled,
                        googleSheetsMode: configResponse.config.google_sheets_mode_enabled,
                        multivendorMode: configResponse.config.multivendor_enabled
                    });
                }
            } catch (configError) {
                console.warn('Could not load configuration:', configError);
            }

        } catch (err) {
            showError(err.message || 'Failed to load dashboard data');
        } finally {
            setLoading(false);
        }
    };

    const handleSync = async () => {
        try {
            setSyncStatus(prev => ({ ...prev, isRunning: true }));

            // Trigger sync for orders and products
            await Promise.all([
                api.syncOrders(),
                api.syncProducts()
            ]);

            // Reload dashboard data
            await loadDashboardData();
            showSuccess('Sync completed successfully');

        } catch (err) {
            showError('Sync failed: ' + err.message);
        } finally {
            setSyncStatus(prev => ({ ...prev, isRunning: false }));
        }
    };

    const formatCurrency = (amount) => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD'
        }).format(amount);
    };

    const formatDate = (dateString) => {
        if (!dateString) return 'Never';
        return new Date(dateString).toLocaleString();
    };

    const quickActions = [
        {
            title: 'Orders Management',
            description: 'Manage WooCommerce orders with database and Google Sheets sync',
            icon: '🛒',
            path: '/orders',
            color: 'primary',
            upcoming: false
        },
        {
            title: 'Products Management',
            description: 'Handle product inventory and stock synchronization',
            icon: '📦',
            path: '/products',
            color: 'secondary',
            upcoming: false
        },
        {
            title: 'Customer Management',
            description: 'Manage customer accounts, billing, and activity tracking',
            icon: '👥',
            path: '/customers',
            color: 'success',
            upcoming: false
        },
        {
            title: 'Settings',
            description: 'Configure modes, Google Sheets integration, and preferences',
            icon: '⚙️',
            path: '/settings',
            color: 'warning',
            upcoming: false
        },
        {
            title: 'Vendors Management',
            description: 'Multivendor support with individual sheet management',
            icon: '🏪',
            path: '/vendors',
            color: 'info',
            upcoming: true
        },
        {
            title: 'System Monitoring',
            description: 'Monitor system health, sync status, and performance metrics',
            icon: '📊',
            path: '/monitoring',
            color: 'info',
            upcoming: true
        },

    ];

    // Load frontend settings if on frontend
    useEffect(() => {
        if (isFrontend) {
            api.getFrontendSettings()
                .then(data => {
                    if (data.success) {
                        setFrontendSettings(data.settings);
                    }
                })
                .catch(err => console.error('Failed to load frontend settings:', err));
        }
    }, [isFrontend]);

    if (loading) {
        return (
            <div className="page dashboard">
                <div className="container container-xl">
                    <LoadingState message="Loading dashboard..." />
                </div>
            </div>
        );
    }

    const hasAnyFeatureEnabled = frontendSettings?.orders_management?.enabled || frontendSettings?.products_management?.enabled;

    // Frontend Dashboard View
    if (isFrontend) {
        return (
            <div className="page dashboard">
                <div className="container container-xl">
                    {/* Frontend Notice */}
                    {!hasAnyFeatureEnabled && (
                        <div className="alert alert-info" style={{ marginBottom: '24px' }}>
                            <strong>ℹ️ No features enabled</strong>
                            <p>Please ask your administrator to enable Orders or Products management from the admin Settings → Quick Actions.</p>
                        </div>
                    )}

                    {/* Header with Date Filter */}
                    <div className="page-header">
                        <div className="page-title">
                            <h1>Dashboard</h1>
                            <p>Welcome back, {userInfo?.display_name || 'User'}</p>
                        </div>
                        <div className="page-actions">
                            <input type="date" className="form-input" placeholder="From" />
                            <input type="date" className="form-input" placeholder="To" />
                            <button className="btn btn-primary btn-sm">Filter</button>
                        </div>
                    </div>

                    {/* Sales Metrics */}
                    <div className="stats-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '20px', marginBottom: '24px' }}>
                        <div className="stat-card">
                            <div className="stat-icon" style={{ background: '#e3f2fd' }}>💰</div>
                            <div className="stat-content">
                                <div className="stat-label">Total Sales</div>
                                <div className="stat-value">{formatCurrency(stats.orders.revenue)}</div>
                                <div className="stat-change positive">+{stats.orders.growth}% from last period</div>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon" style={{ background: '#f3e5f5' }}>📦</div>
                            <div className="stat-content">
                                <div className="stat-label">Total Orders</div>
                                <div className="stat-value">{stats.orders.total}</div>
                                <div className="stat-change">{stats.orders.pending} pending</div>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon" style={{ background: '#e8f5e9' }}>📊</div>
                            <div className="stat-content">
                                <div className="stat-label">Average Order Value</div>
                                <div className="stat-value">
                                    {stats.orders.total > 0 ? formatCurrency(stats.orders.revenue / stats.orders.total) : '$0.00'}
                                </div>
                                <div className="stat-change">Per order</div>
                            </div>
                        </div>
                    </div>

                    {/* Revenue Chart */}
                    <div className="card mb-6">
                        <div className="card-header">
                            <h3>Revenue Overview</h3>
                            <p>Sales performance over time</p>
                        </div>
                        <div className="card-content">
                            <div style={{ padding: '40px', textAlign: 'center', background: '#f5f5f5', borderRadius: '8px' }}>
                                <div style={{ fontSize: '48px', marginBottom: '16px' }}>📈</div>
                                <p style={{ color: '#666' }}>Revenue chart will be displayed here</p>
                                <p style={{ fontSize: '14px', color: '#999' }}>Integration with charting library coming soon</p>
                            </div>
                        </div>
                    </div>

                    {/* Top Products */}
                    <div className="card">
                        <div className="card-header">
                            <h3>Top Products Performance</h3>
                            <p>Best selling products</p>
                        </div>
                        <div className="card-content">
                            <div className="table-responsive">
                                <table className="table">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Stock</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td colSpan="4" style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                                                No data available
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Backend/Admin Dashboard View
    return (
        <div className="page dashboard">
            <div className="container container-xl">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <h1>Shop Explorer Dashboard</h1>
                        <p>{userInfo ? `Welcome back, ${userInfo.display_name}` : 'Unified WooCommerce management with dual-mode operation'}</p>
                    </div>
                    <div className="page-actions">
                        <button
                            className="btn btn-secondary btn-sm"
                            onClick={loadDashboardData}
                            disabled={loading}
                        >
                            🔄 Refresh
                        </button>
                        <button
                            className={`btn btn-primary btn-sm ${syncStatus.isRunning ? 'btn-loading' : ''}`}
                            onClick={handleSync}
                            disabled={syncStatus.isRunning}
                        >
                            {syncStatus.isRunning ? (
                                <>
                                    <div className="spinner"></div>
                                    Exporting...
                                </>
                            ) : (
                                <>
                                    🔄 Export Data
                                    {syncStatus.pendingOperations > 0 && (
                                        <span className="chip chip-warning">{syncStatus.pendingOperations}</span>
                                    )}
                                </>
                            )}
                        </button>
                    </div>
                </div>

                {/* Mode Status */}
                <div className="card mb-6">
                    <div className="card-header">
                        <h3>Current Mode Status</h3>
                        <p>Active operation modes for your Shop Explorer</p>
                    </div>
                    <div className="card-content">
                        <div className="mode-chips">
                            <div className={`chip ${modes.databaseMode ? 'chip-primary' : 'chip-secondary'}`}>
                                Database Mode
                            </div>
                            {/* <div className={`chip ${modes.googleSheetsMode ? 'chip-success' : 'chip-secondary'}`}>
                                Export mode
                            </div> */}
                            {/* <div className={`chip ${modes.multivendorMode ? 'chip-warning' : 'chip-secondary'}`}>
                                Multivendor Mode
                            </div> */}
                        </div>
                    </div>
                </div>

                {/* Stats Cards */}
                <div className="stats-grid grid grid-cols-4 mb-6">
                    <div className="stat-card card card-hover">
                        <div className="stat-content">
                            <div className="stat-icon orders">🛒</div>
                            <div className="stat-info">
                                <div className="stat-number">{stats.orders.total}</div>
                                <div className="stat-label">Total Orders</div>
                                <div className="stat-growth">
                                    {stats.orders.growth > 0 ? '📈' : stats.orders.growth < 0 ? '📉' : '➖'}
                                    {stats.orders.growth > 0 ? '+' : ''}{stats.orders.growth}%
                                </div>
                            </div>
                        </div>
                        <div className="stat-details">
                            <div className="chip chip-warning">{stats.orders.pending} Pending</div>
                            <div className="chip chip-success">{stats.orders.completed} Completed</div>
                        </div>
                    </div>

                    <div className="stat-card card card-hover">
                        <div className="stat-content">
                            <div className="stat-icon products">📦</div>
                            <div className="stat-info">
                                <div className="stat-number">{stats.products.total}</div>
                                <div className="stat-label">Products</div>
                                {stats.products.low_stock > 0 && (
                                    <div className="stat-warning">
                                        ⚠️ {stats.products.low_stock} Low Stock
                                    </div>
                                )}
                            </div>
                        </div>
                        <div className="stat-details">
                            <div className="chip chip-success">{stats.products.in_stock} In Stock</div>
                            <div className="chip chip-danger">{stats.products.out_of_stock} Out of Stock</div>
                        </div>
                    </div>

                    <div className="stat-card card card-hover">
                        <div className="stat-content">
                            <div className="stat-icon revenue">💰</div>
                            <div className="stat-info">
                                <div className="stat-number">{formatCurrency(stats.orders.revenue || 0)}</div>
                                <div className="stat-label">Revenue</div>
                                <div className="stat-period">This Month</div>
                            </div>
                        </div>
                    </div>

                    {modes.multivendorMode && (
                        <div className="stat-card card card-hover">
                            <div className="stat-content">
                                <div className="stat-icon vendors">👥</div>
                                <div className="stat-info">
                                    <div className="stat-number">{stats.vendors.total}</div>
                                    <div className="stat-label">Vendors</div>
                                </div>
                            </div>
                            <div className="stat-details">
                                <div className="chip chip-success">{stats.vendors.active} Active</div>
                                {stats.vendors.pending > 0 && (
                                    <div className="chip chip-warning">{stats.vendors.pending} Pending</div>
                                )}
                            </div>
                        </div>
                    )}
                </div>

                {/* Main Content Grid */}
                <div className="grid grid-cols-3 gap-6">
                    {/* Left Column - Quick Actions */}
                    <div className="col-span-2">
                        <h2 className="section-title">Quick Actions</h2>
                        <div className="quick-actions grid grid-cols-2 gap-4">
                            {quickActions.map((action, index) => (
                                <div key={index} className={`action-card card card-hover ${action.upcoming ? 'upcoming-feature' : ''}`}>
                                    <div className="card-content">
                                        <div className="action-header">
                                            <div className="action-icon">{action.icon}</div>
                                            <h3>
                                                {action.title}
                                                {action.upcoming && <span className="upcoming-badge">Coming Soon</span>}
                                            </h3>
                                        </div>
                                        <p>{action.description}</p>
                                    </div>
                                    <div className="card-footer">
                                        <button
                                            className={`btn btn-${action.color} btn-sm`}
                                            onClick={() => !action.upcoming && navigate(action.path)}
                                            disabled={action.upcoming}
                                        >
                                            {action.upcoming ? 'Coming Soon' : 'Open'}
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Right Column - Activity & Status */}
                    <div className="sidebar">
                        {/* Export Status */}
                        {modes.googleSheetsMode && (
                            <div className="card mb-4">
                                <div className="card-header">
                                    <h3>Export Status</h3>
                                </div>
                                <div className="card-content">
                                    <div className="sync-status">
                                        {syncStatus.isRunning ? (
                                            <div className="status-item">
                                                <div className="spinner"></div>
                                                <span>Syncing...</span>
                                            </div>
                                        ) : (
                                            <div className="status-item">
                                                <div className="status-indicator success">✅</div>
                                                <span>Ready</span>
                                            </div>
                                        )}
                                    </div>
                                    <div className="sync-info">
                                        <p className="text-sm text-gray-600">
                                            Last Export: {formatDate(syncStatus.lastSync)}
                                        </p>
                                        {syncStatus.pendingOperations > 0 && (
                                            <div className="chip chip-warning">
                                                ⏱️ {syncStatus.pendingOperations} pending
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}


                        {/* Recent Activity */}
                        <div className="card">
                            <div className="card-header">
                                <h3>Recent Activity</h3>
                            </div>
                            <div className="card-content">
                                {recentActivity.length > 0 ? (
                                    <div className="activity-list">
                                        {recentActivity.slice(0, 5).map((activity, index) => (
                                            <div key={index} className="activity-item">
                                                <div className="activity-icon">
                                                    {activity.type === 'order' && '🛒'}
                                                    {activity.type === 'product' && '📦'}
                                                    {activity.type === 'sync' && '🔄'}
                                                </div>
                                                <div className="activity-content">
                                                    <div className="activity-title">{activity.title}</div>
                                                    <div className="activity-time text-sm text-gray-600">{activity.time}</div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <p className="text-gray-600">No recent activity</p>
                                )}
                            </div>
                        </div>

                        {/* Product Showcase Promotion */}
                        <div className="card mb-4 promo-card">
                            <div className="card-header">
                                <h3>🎨 Customize Product Showcase</h3>
                            </div>
                            <div className="card-content">
                                <p className="text-sm text-gray-600" style={{ marginBottom: '12px' }}>
                                    Create stunning WooCommerce Product layouts and interactive Product showcases using Grid, Slider, List, Card, Gallery, Table, and more.
                                </p>
                                <button
                                    className="btn btn-primary btn-sm"
                                    style={{ width: '100%' }}
                                    onClick={() => {
                                        window.location.href = '/wp-admin/plugin-install.php?s=product%20display%20wpazleen&tab=search&type=term';
                                    }}
                                >
                                    Install Plugin
                                </button>
                            </div>
                        </div>


                    </div>
                </div>
            </div>
        </div>
    );
};

export default Dashboard;