import React, { useState, useEffect, useRef } from 'react';
import api from '../utils/api';
import { useToast } from '../App';
import OrderSyncConfig from '../components/OrderSyncConfig';
import ProductSyncConfig from '../components/ProductSyncConfig';
import QuickActions from '../components/QuickActions';
import LoadingState from '../components/LoadingState';

const Settings = () => {
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [activeTab, setActiveTab] = useState('general');

    // Google Sheets Setup State
    const [googleSheetsConnected, setGoogleSheetsConnected] = useState(false);
    const [setupWizardOpen, setSetupWizardOpen] = useState(false);
    const [serviceAccountEmail, setServiceAccountEmail] = useState('');
    const [orderSyncConfigOpen, setOrderSyncConfigOpen] = useState(false);
    const [productSyncConfigOpen, setProductSyncConfigOpen] = useState(false);

    const [settings, setSettings] = useState({
        // General Settings
        database_mode_enabled: true,
        google_sheets_mode_enabled: false,
        multivendor_enabled: false,
        auto_sync_enabled: false,
        sync_interval: 30,

        // Google Sheets Settings
        spreadsheet_url: '',
        service_account_key: '',
        sheet_names: {
            orders: 'Sheets1',
            products: 'Sheets2',
            customers: 'Sheets3',
            // vendors: 'Sheets3'
        },
        configured_sheets: {},

        // Sync Settings
        sync_orders: true,
        sync_products: true,
        sync_customers: false,
        batch_size: 100,

        // Notification Settings
        email_notifications: true,
        notification_email: '',
        sync_success_notifications: false,
        sync_error_notifications: true
    });

    const tabs = [
        { id: 'general', label: 'General', icon: '⚙️' },
        { id: 'quick-actions', label: 'Quick Actions', icon: '⚡' },
        { id: 'google-sheets', label: 'Google Sheets', icon: '📊', disabled: !settings.google_sheets_mode_enabled },
        { id: 'sync', label: 'Sync Settings', icon: '🔄' },
        { id: 'notifications', label: 'Notifications', icon: '🔔' },
        { id: 'more', label: 'More', icon: '➕' }
    ];



    useEffect(() => {
        loadSettings();
    }, []);

    const loadSettings = async () => {
        try {
            setLoading(true);
            const response = await api.getSettings();

            if (response.success) {
                setSettings(prev => ({
                    ...prev,
                    ...response.settings
                }));

                // Check Google Sheets connection
                await checkGoogleSheetsConnection();
            } else {
                throw new Error(response.message || 'Failed to load settings');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const checkGoogleSheetsConnection = async () => {
        try {
            const response = await api.testGoogleSheetsConnection();
            if (response.success) {
                setGoogleSheetsConnected(true);
                setServiceAccountEmail(response.service_account_email || '');
            } else {
                setGoogleSheetsConnected(false);
            }
        } catch (err) {
            setGoogleSheetsConnected(false);
        }
    };



    const handleTestConnection = async () => {
        try {
            const response = await api.testGoogleSheetsConnection();

            if (response.success) {
                setGoogleSheetsConnected(true);
                showSuccess('Google Sheets connection verified successfully!');
            } else {
                throw new Error(response.message || 'Connection test failed');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleRevokeCredentials = async () => {
        try {
            const response = await api.revokeSHOPEX_GoogleSheetsAuth();

            if (response.success) {
                setGoogleSheetsConnected(false);
                setServiceAccountEmail('');
                setSettings(prev => ({
                    ...prev,
                    configured_sheets: {}
                }));
                showSuccess('Google Sheets credentials removed successfully');
            } else {
                throw new Error(response.message || 'Failed to revoke credentials');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleSettingChange = (key, value) => {
        setSettings(prev => ({
            ...prev,
            [key]: value
        }));
    };

    const handleNestedSettingChange = (parent, key, value) => {
        setSettings(prev => ({
            ...prev,
            [parent]: {
                ...prev[parent],
                [key]: value
            }
        }));
    };

    const saveSettings = async () => {
        try {
            setSaving(true);
            const response = await api.updateSettings(settings);

            if (response.success) {
                showSuccess('Settings saved successfully');
            } else {
                throw new Error(response.message || 'Failed to save settings');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSaving(false);
        }
    };


    if (loading) {
        return (
            <div className="page">
                <div className="container container-xl">
                    <LoadingState message="Loading settings..." />
                </div>
            </div>
        );
    }

    return (
        <div className="page settings">
            <div className="container container-xl">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <h1>Settings</h1>
                        <p>Configure modes, Google Sheets integration, and preferences</p>
                    </div>
                    <div className="page-actions">
                        <button
                            className="btn btn-secondary btn-sm"
                            onClick={loadSettings}
                            disabled={loading}
                        >
                            🔄 Refresh
                        </button>
                        <button
                            className={`btn btn-primary btn-sm ${saving ? 'btn-loading' : ''}`}
                            onClick={saveSettings}
                            disabled={saving}
                        >
                            {saving ? (
                                <>
                                    <div className="spinner"></div>
                                    Saving...
                                </>
                            ) : (
                                '💾 Save Settings'
                            )}
                        </button>
                    </div>
                </div>

                <div className="settings-layout">
                    {/* Tabs Navigation */}
                    <div className="settings-tabs">
                        {tabs.map(tab => (
                            <button
                                key={tab.id}
                                className={`tab-button ${activeTab === tab.id ? 'active' : ''} ${tab.disabled ? 'disabled' : ''}`}
                                onClick={() => !tab.disabled && setActiveTab(tab.id)}
                                disabled={tab.disabled}
                            >
                                <span className="tab-icon">{tab.icon}</span>
                                <span className="tab-label">{tab.label}</span>
                            </button>
                        ))}
                    </div>

                    {/* Tab Content */}
                    <div className="settings-content">
                        {/* General Settings */}
                        {activeTab === 'general' && (
                            <div className="tab-panel">
                                <div className="card">
                                    <div className="card-header">
                                        <h3>Operation Modes</h3>
                                        <p>Configure how Shop Explorer operates</p>
                                    </div>
                                    <div className="card-content">
                                        <div className="settings-group">
                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Database Mode</label>
                                                    <p className="setting-description">
                                                        Store and manage data in WordPress database
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.database_mode_enabled}
                                                            onChange={(e) => handleSettingChange('database_mode_enabled', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Google Sheets Mode</label>
                                                    <p className="setting-description">
                                                        Export data with Google Sheets for external access
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.google_sheets_mode_enabled}
                                                            onChange={(e) => handleSettingChange('google_sheets_mode_enabled', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item upcoming-feature">
                                                <div className="setting-info">
                                                    <label className="setting-label">
                                                        Multivendor Mode
                                                        <span className="upcoming-badge">Coming Soon</span>
                                                    </label>
                                                    <p className="setting-description">
                                                        Enable multivendor support with individual sheet management
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.multivendor_enabled}
                                                            onChange={(e) => handleSettingChange('multivendor_enabled', e.target.checked)}
                                                            disabled
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item upcoming-feature">
                                                <div className="setting-info">
                                                    <label className="setting-label">
                                                        Auto Export
                                                        <span className="upcoming-badge">Coming Soon</span>
                                                    </label>
                                                    <p className="setting-description">
                                                        Automatically export data at regular intervals
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.auto_sync_enabled}
                                                            onChange={(e) => handleSettingChange('auto_sync_enabled', e.target.checked)}
                                                            disabled
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            {settings.auto_sync_enabled && (
                                                <div className="setting-item">
                                                    <div className="setting-info">
                                                        <label className="setting-label">Export Interval (minutes)</label>
                                                        <p className="setting-description">
                                                            How often to automatically export data
                                                        </p>
                                                    </div>
                                                    <div className="setting-control">
                                                        <select
                                                            value={settings.sync_interval}
                                                            onChange={(e) => handleSettingChange('sync_interval', parseInt(e.target.value))}
                                                        >
                                                            <option value={15}>15 minutes</option>
                                                            <option value={30}>30 minutes</option>
                                                            <option value={60}>1 hour</option>
                                                            <option value={120}>2 hours</option>
                                                            <option value={360}>6 hours</option>
                                                            <option value={720}>12 hours</option>
                                                            <option value={1440}>24 hours</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Quick Actions */}
                        {activeTab === 'quick-actions' && (
                            <div className="tab-panel">
                                <QuickActions />
                            </div>
                        )}

                        {/* Google Sheets Settings */}
                        {activeTab === 'google-sheets' && settings.google_sheets_mode_enabled && (
                            <div className="tab-panel">
                                {/* Connection Status Card */}
                                <div className="card">
                                    <div className="card-header">
                                        <h3>Google Sheets Connection Status</h3>
                                        <div className={`chip ${googleSheetsConnected ? 'chip-success' : 'chip-danger'}`}>
                                            {googleSheetsConnected ? '✅ Connected' : '❌ Not Connected'}
                                        </div>
                                    </div>
                                    <div className="card-content">
                                        {googleSheetsConnected ? (
                                            <div className="connection-success">
                                                <div className="success-info">
                                                    <p>Your Google Sheets integration is active and ready to export data.</p>
                                                    {serviceAccountEmail && (
                                                        <p className="service-account-info">
                                                            <strong>Service Account:</strong> {serviceAccountEmail}
                                                        </p>
                                                    )}
                                                </div>
                                                <div className="connection-actions flex gap-2 mt-4">
                                                    <button
                                                        className="btn btn-secondary btn-sm"
                                                        onClick={handleTestConnection}
                                                    >
                                                        🔍 Test Connection
                                                    </button>
                                                    <button
                                                        className="btn btn-primary btn-sm"
                                                        onClick={() => setSetupWizardOpen(true)}
                                                    >
                                                        ⚙️ Edit Configuration
                                                    </button>
                                                    <button
                                                        className="btn btn-danger btn-sm"
                                                        onClick={handleRevokeCredentials}
                                                    >
                                                        🗑️ Disconnect
                                                    </button>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="connection-setup">
                                                <div className="setup-info">
                                                    <h4>🚀 Get Started with Google Sheets Integration</h4>
                                                    <p>Connect your WooCommerce store to Google Sheets for real-time data synchronization.</p>
                                                    <div className="benefits-list">
                                                        <div className="benefit-item">✅ Real-time sync of orders, products, and vendor data</div>
                                                        <div className="benefit-item">✅ Customizable field mappings</div>
                                                        <div className="benefit-item">✅ Automatic data updates</div>
                                                        <div className="benefit-item">✅ Easy collaboration with your team</div>
                                                    </div>
                                                </div>
                                                <div className="setup-action">
                                                    <button
                                                        className="btn btn-primary btn-lg"
                                                        onClick={() => setSetupWizardOpen(true)}
                                                    >
                                                        🎯 Start Configuration Wizard
                                                    </button>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Configured Sheets (if connected) */}
                                {googleSheetsConnected && settings.configured_sheets && Object.keys(settings.configured_sheets).length > 0 && (
                                    <div className="card">
                                        <div className="card-header">
                                            <h3>📊 Active Sheet Integrations</h3>
                                            <p>Your currently configured Google Sheets</p>
                                        </div>
                                        <div className="card-content">
                                            <div className="sheets-grid grid grid-cols-1 gap-4">
                                                {Object.entries(settings.configured_sheets).map(([type, config]) => (
                                                    <div key={type} className="sheet-item">
                                                        <div className="sheet-info">
                                                            <div className="sheet-header">
                                                                <h4>{type.charAt(0).toUpperCase() + type.slice(1)} Data</h4>
                                                                <div className="chip chip-success">Active</div>
                                                            </div>
                                                            <div className="sheet-details">
                                                                <p><strong>Tab Name:</strong> {config.sheet_name}</p>
                                                                <p><strong>Spreadsheet:</strong> {config.spreadsheet_url}</p>
                                                            </div>
                                                        </div>
                                                        <div className="sheet-actions">
                                                            <button
                                                                className="btn btn-secondary btn-sm"
                                                                onClick={() => window.open(config.spreadsheet_url, '_blank')}
                                                            >
                                                                🔗 Open Sheet
                                                            </button>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                )}



                                {/* Setup Wizard Modal */}
                                {setupWizardOpen && (
                                    <GoogleSheetsSetupWizard
                                        onClose={() => setSetupWizardOpen(false)}
                                        onComplete={() => {
                                            setSetupWizardOpen(false);
                                            checkGoogleSheetsConnection();
                                            loadSettings();
                                        }}
                                        isConnected={googleSheetsConnected}
                                        currentSettings={settings}
                                    />
                                )}

                                {/* Order Sync Config Modal */}
                                {orderSyncConfigOpen && (
                                    <OrderSyncConfig
                                        onClose={() => setOrderSyncConfigOpen(false)}
                                        onSuccess={() => {
                                            showSuccess('Orders synced successfully!');
                                        }}
                                    />
                                )}

                                {/* Product Sync Config Modal */}
                                {productSyncConfigOpen && (
                                    <ProductSyncConfig
                                        onClose={() => setProductSyncConfigOpen(false)}
                                        onSuccess={() => {
                                            showSuccess('Products synced successfully!');
                                        }}
                                    />
                                )}
                            </div>
                        )}

                        {/* Sync Settings */}
                        {activeTab === 'sync' && (
                            <div className="tab-panel">
                                <div className="card">
                                    <div className="card-header">
                                        <h3>Export Configuration</h3>
                                        <p>Configure what data to sync and how</p>
                                    </div>
                                    <div className="card-content">
                                        <div className="settings-group">
                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Export Orders</label>
                                                    <p className="setting-description">
                                                        Include orders in synchronization
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.sync_orders}
                                                            onChange={(e) => handleSettingChange('sync_orders', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Export Products</label>
                                                    <p className="setting-description">
                                                        Include products in synchronization
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.sync_products}
                                                            onChange={(e) => handleSettingChange('sync_products', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Export Customers</label>
                                                    <p className="setting-description">
                                                        Include customers in synchronization
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.sync_customers}
                                                            onChange={(e) => handleSettingChange('sync_customers', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Batch Size</label>
                                                    <p className="setting-description">
                                                        Number of records to process in each batch
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <select
                                                        value={settings.batch_size}
                                                        onChange={(e) => handleSettingChange('batch_size', parseInt(e.target.value))}
                                                    >
                                                        <option value={50}>50 records</option>
                                                        <option value={100}>100 records</option>
                                                        <option value={200}>200 records</option>
                                                        <option value={500}>500 records</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="card">
                                    <div className="card-header">
                                        <h3>Manual Export Actions</h3>
                                        <p>Manually export data to Google Sheets</p>
                                    </div>
                                    <div className="card-content">
                                        <div className="sync-actions-grid">
                                            <div className="sync-action-card">
                                                <div className="sync-action-icon">📊</div>
                                                <h4>Export Orders</h4>
                                                <p>Export all WooCommerce orders to Google Sheets</p>
                                                <button
                                                    className="btn btn-primary"
                                                    onClick={() => setOrderSyncConfigOpen(true)}
                                                >
                                                    Configure & Export Orders
                                                </button>
                                            </div>

                                            <div className="sync-action-card">
                                                <div className="sync-action-icon">📦</div>
                                                <h4>Export Products</h4>
                                                <p>Export all WooCommerce products to Google Sheets</p>
                                                <button
                                                    className="btn btn-primary"
                                                    onClick={() => setProductSyncConfigOpen(true)}
                                                >
                                                    Configure & Export Products
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        )}

                        {/* Notifications Settings */}
                        {activeTab === 'notifications' && (
                            <div className="tab-panel">
                                <div className="card upcoming-feature">
                                    <div className="card-header">
                                        <h3>
                                            Notification Settings
                                            <span className="upcoming-badge">Coming Soon</span>
                                        </h3>
                                        <p>Configure email notifications and alerts</p>
                                    </div>
                                    <div className="card-content">
                                        <div className="settings-group">
                                            <div className="setting-item">
                                                <div className="setting-info">
                                                    <label className="setting-label">Email Notifications</label>
                                                    <p className="setting-description">
                                                        Enable email notifications for sync events
                                                    </p>
                                                </div>
                                                <div className="setting-control">
                                                    <label className="switch">
                                                        <input
                                                            type="checkbox"
                                                            checked={settings.email_notifications}
                                                            onChange={(e) => handleSettingChange('email_notifications', e.target.checked)}
                                                        />
                                                        <span className="slider"></span>
                                                    </label>
                                                </div>
                                            </div>

                                            {settings.email_notifications && (
                                                <>
                                                    <div className="form-group">
                                                        <label>Notification Email</label>
                                                        <input
                                                            type="email"
                                                            value={settings.notification_email}
                                                            onChange={(e) => handleSettingChange('notification_email', e.target.value)}
                                                            placeholder="Enter email address for notifications"
                                                        />
                                                    </div>

                                                    <div className="setting-item">
                                                        <div className="setting-info">
                                                            <label className="setting-label">Sync Success Notifications</label>
                                                            <p className="setting-description">
                                                                Get notified when sync completes successfully
                                                            </p>
                                                        </div>
                                                        <div className="setting-control">
                                                            <label className="switch">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={settings.sync_success_notifications}
                                                                    onChange={(e) => handleSettingChange('sync_success_notifications', e.target.checked)}
                                                                />
                                                                <span className="slider"></span>
                                                            </label>
                                                        </div>
                                                    </div>

                                                    <div className="setting-item">
                                                        <div className="setting-info">
                                                            <label className="setting-label">Sync Error Notifications</label>
                                                            <p className="setting-description">
                                                                Get notified when sync encounters errors
                                                            </p>
                                                        </div>
                                                        <div className="setting-control">
                                                            <label className="switch">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={settings.sync_error_notifications}
                                                                    onChange={(e) => handleSettingChange('sync_error_notifications', e.target.checked)}
                                                                />
                                                                <span className="slider"></span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* More Tab */}
                        {activeTab === 'more' && (
                            <div className="tab-panel">
                                <div className="plugins-grid">
                                    {/* Product Display Plugin */}
                                    <div className="card plugin-card">
                                        <div className="plugin-header">
                                            <div className="plugin-icon">
                                                <img 
                                                    src="https://ps.w.org/product-display/assets/icon-128x128.png?rev=3390638" 
                                                    alt="Product Display"
                                                />
                                            </div>
                                            <div className="plugin-title">
                                                <h3>Product Display for WooCommerce</h3>
                                                <p className="plugin-tagline">Enhance your product showcase</p>
                                            </div>
                                        </div>
                                        <div className="card-content">
                                            <p className="plugin-description">
                                                Create stunning WooCommerce Product layouts and interactive Product showcases using Grid, Slider, List, Card, Gallery, Table, and more.
                                            </p>
                                            <div className="plugin-features">
                                                <span className="feature-badge">✨ Multiple Layouts</span>
                                                <span className="feature-badge">📱 Responsive</span>
                                                <span className="feature-badge">🎨 Customizable</span>
                                            </div>
                                            <button
                                                className="btn btn-primary btn-block"
                                                onClick={() => {
                                                    window.location.href = '/wp-admin/plugin-install.php?s=product%20display%20wpazleen&tab=search&type=term';
                                                }}
                                            >
                                                Install Now →
                                            </button>
                                            <p className="plugin-author">⭐ Free by WPAzleen</p>
                                        </div>
                                    </div>

                                    {/* Activity Guard Plugin */}
                                    <div className="card plugin-card">
                                        <div className="plugin-header">
                                            <div className="plugin-icon">
                                                <img 
                                                    src="https://ps.w.org/notifier-to-slack/assets/icon.svg?rev=3388086" 
                                                    alt="Activity Guard"
                                                />
                                            </div>
                                            <div className="plugin-title">
                                                <h3>Activity Guard</h3>
                                                <p className="plugin-tagline">Complete Security & Activity Log</p>
                                            </div>
                                        </div>
                                        <div className="card-content">
                                            <p className="plugin-description">
                                                Track everything on your WordPress site. Monitor user behavior, admin changes, WooCommerce events + analytics, with instant notifier support.
                                            </p>
                                            <div className="plugin-features">
                                                <span className="feature-badge">🛡️ Security</span>
                                                <span className="feature-badge">📊 Analytics</span>
                                                <span className="feature-badge">🔔 Notifications</span>
                                            </div>
                                            <button
                                                className="btn btn-primary btn-block"
                                                onClick={() => {
                                                    window.location.href = '/wp-admin/plugin-install.php?s=activity%20guard%20wpazleen&tab=search&type=term';
                                                }}
                                            >
                                                Install Now →
                                            </button>
                                            <p className="plugin-author">⭐ Free by WPAzleen</p>
                                        </div>
                                    </div>

                                    {/* AskAny Plugin */}
                                    <div className="card plugin-card">
                                        <div className="plugin-header">
                                            <div className="plugin-icon">
                                                <img 
                                                    src="https://ps.w.org/askany/assets/icon-128x128.png?rev=3294851" 
                                                    alt="AskAny"
                                                />
                                            </div>
                                            <div className="plugin-title">
                                                <h3>AskAny</h3>
                                                <p className="plugin-tagline">AI-Powered Chat Assistant</p>
                                            </div>
                                        </div>
                                        <div className="card-content">
                                            <p className="plugin-description">
                                                Advanced AI chatbot featuring SSE technology, powered by OpenAI, DeepSeek, and Gemini. Delivers instant responses for customer support.
                                            </p>
                                            <div className="plugin-features">
                                                <span className="feature-badge">🤖 AI Powered</span>
                                                <span className="feature-badge">⚡ Instant</span>
                                                <span className="feature-badge">💬 Chat Support</span>
                                            </div>
                                            <button
                                                className="btn btn-primary btn-block"
                                                onClick={() => {
                                                    window.location.href = '/wp-admin/plugin-install.php?s=askany%20wpazleen&tab=search&type=term';
                                                }}
                                            >
                                                Install Now →
                                            </button>
                                            <p className="plugin-author">⭐ Free by WPAzleen</p>
                                        </div>
                                    </div>

                                    {/* Simple Form Plugin */}
                                    <div className="card plugin-card">
                                        <div className="plugin-header">
                                            <div className="plugin-icon">
                                                <img 
                                                    src="https://ps.w.org/simple-form/assets/icon-128x128.png?rev=3399184" 
                                                    alt="Simple Form"
                                                />
                                            </div>
                                            <div className="plugin-title">
                                                <h3>Simple Form</h3>
                                                <p className="plugin-tagline">Ultimate Form Builder</p>
                                            </div>
                                        </div>
                                        <div className="card-content">
                                            <p className="plugin-description">
                                                Comprehensive form builder with Quiz, Poll, Multi Step Forms, Conditional Logic, Form Analytics & Advanced Integrations. No coding required!
                                            </p>
                                            <div className="plugin-features">
                                                <span className="feature-badge">📝 Drag & Drop</span>
                                                <span className="feature-badge">📊 Analytics</span>
                                                <span className="feature-badge">🔗 Integrations</span>
                                            </div>
                                            <button
                                                className="btn btn-primary btn-block"
                                                onClick={() => {
                                                    window.location.href = '/wp-admin/plugin-install.php?s=simple%20form%20wpazleen&tab=search&type=term';
                                                }}
                                            >
                                                Install Now →
                                            </button>
                                            <p className="plugin-author">⭐ Free by WPAzleen</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

// Google Sheets Setup Wizard Component
const GoogleSheetsSetupWizard = ({ onClose, onComplete, isConnected, currentSettings }) => {
    const { showSuccess, showError } = useToast();
    const [currentStep, setCurrentStep] = useState(0);
    const [loading, setLoading] = useState(false);
    const fileInputRef = useRef(null);

    const [wizardData, setWizardData] = useState(() => {
        // Convert configured_sheets to wizard format
        const convertedSheetConfigs = {
            orders: { enabled: false, tabName: 'Orders' },
            products: { enabled: false, tabName: 'Products' },
            customers: { enabled: false, tabName: 'Customers' },
            // vendors: { enabled: false, tabName: 'Vendors' }
        };

        // Initialize with current settings if available
        if (currentSettings) {
            if (currentSettings.configured_sheets) {
                Object.entries(currentSettings.configured_sheets).forEach(([type, config]) => {
                    if (convertedSheetConfigs[type]) {
                        convertedSheetConfigs[type] = {
                            enabled: true,
                            tabName: config.sheet_name || config.tabName || type.charAt(0).toUpperCase() + type.slice(1)
                        };
                    }
                });
            }

            // Also check sheet_configs format
            if (currentSettings.sheet_configs) {
                Object.entries(currentSettings.sheet_configs).forEach(([type, config]) => {
                    if (convertedSheetConfigs[type] && config.enabled) {
                        convertedSheetConfigs[type] = {
                            enabled: config.enabled || false,
                            tabName: config.tabName || config.sheet_name || type.charAt(0).toUpperCase() + type.slice(1)
                        };
                    }
                });
            }

            const initialData = {
                credentials: null, // Don't pre-fill credentials for security
                serviceAccountEmail: '', // This will be loaded from API
                spreadsheetUrl: currentSettings.spreadsheet_url || '',
                sheetConfigs: convertedSheetConfigs
            };

            console.log('Wizard initialized with existing settings:', initialData);
            console.log('Current settings received:', currentSettings);
            return initialData;
        }

        // Default values for new setup
        const defaultData = {
            credentials: null,
            serviceAccountEmail: '',
            spreadsheetUrl: '',
            sheetConfigs: {
                orders: { enabled: true, tabName: 'Orders' },
                products: { enabled: false, tabName: 'Products' },
                customers: { enabled: false, tabName: 'Customers' },
                // vendors: { enabled: false, tabName: 'Vendors' }
            }
        };

        console.log('Wizard initialized with default settings:', defaultData);
        return defaultData;
    });

    const steps = [
        { title: 'Upload Credentials', icon: '📁' },
        { title: 'Configure Sheets', icon: '📊' },
        { title: 'Grant Access', icon: '🔑' },
        { title: 'Complete Setup', icon: '✅' }
    ];

    // Debug: Log the props being passed to wizard
    useEffect(() => {
        console.log('Wizard props:', { isConnected, currentSettings });
    }, [isConnected, currentSettings]);

    // Reinitialize wizard data when currentSettings change (for edit mode)
    useEffect(() => {
        if (currentSettings) {
            // Convert configured_sheets to wizard format
            const convertedSheetConfigs = {
                orders: { enabled: false, tabName: 'Orders' },
                products: { enabled: false, tabName: 'Products' },
                customers: { enabled: false, tabName: 'Customers' },
                // vendors: { enabled: false, tabName: 'Vendors' }
            };

            if (currentSettings.configured_sheets) {
                Object.entries(currentSettings.configured_sheets).forEach(([type, config]) => {
                    if (convertedSheetConfigs[type]) {
                        convertedSheetConfigs[type] = {
                            enabled: true,
                            tabName: config.sheet_name || config.tabName || type.charAt(0).toUpperCase() + type.slice(1)
                        };
                    }
                });
            }

            // Also check sheet_configs format
            if (currentSettings.sheet_configs) {
                Object.entries(currentSettings.sheet_configs).forEach(([type, config]) => {
                    if (convertedSheetConfigs[type]) {
                        convertedSheetConfigs[type] = {
                            enabled: config.enabled || false,
                            tabName: config.tabName || config.sheet_name || type.charAt(0).toUpperCase() + type.slice(1)
                        };
                    }
                });
            }

            setWizardData(prev => ({
                ...prev,
                spreadsheetUrl: currentSettings.spreadsheet_url || '',
                sheetConfigs: convertedSheetConfigs
            }));

            console.log('Wizard data updated with current settings:', {
                spreadsheet_url: currentSettings.spreadsheet_url,
                configured_sheets: currentSettings.configured_sheets,
                sheet_configs: currentSettings.sheet_configs
            });
        }
    }, [currentSettings]);

    // Load service account email when editing existing configuration
    useEffect(() => {
        if (isConnected && !wizardData.serviceAccountEmail) {
            const loadServiceAccountEmail = async () => {
                try {
                    const response = await api.testGoogleSheetsConnection();
                    if (response.success && response.service_account_email) {
                        setWizardData(prev => ({
                            ...prev,
                            serviceAccountEmail: response.service_account_email
                        }));
                    }
                } catch (err) {
                    console.error('Failed to load service account email:', err);
                }
            };
            loadServiceAccountEmail();
        }
    }, [isConnected]);

    const handleFileUpload = async (event) => {
        const file = event.target.files[0];
        if (!file) return;

        if (file.type !== 'application/json') {
            showError('Please upload a valid JSON file');
            return;
        }

        try {
            setLoading(true);
            const fileContent = await file.text();

            // Clean the JSON content to remove any potential BOM or extra whitespace
            const cleanContent = fileContent.trim().replace(/^\uFEFF/, '');

            let credentials;
            try {
                credentials = JSON.parse(cleanContent);
            } catch (parseError) {
                throw new Error(`Invalid JSON format: ${parseError.message}. Please ensure you're uploading a valid Google Service Account JSON file.`);
            }

            if (!credentials.client_email || !credentials.private_key) {
                throw new Error('Invalid service account file. Missing required fields (client_email or private_key).');
            }

            const response = await api.uploadGoogleSheetsCredentials(credentials);

            if (response.success) {
                setWizardData(prev => ({
                    ...prev,
                    credentials: credentials,
                    serviceAccountEmail: credentials.client_email
                }));
                showSuccess('Credentials uploaded successfully!');
                setCurrentStep(1);
            } else {
                throw new Error(response.message || 'Failed to upload credentials');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setLoading(false);
            event.target.value = '';
        }
    };

    const handleNext = () => {
        // Validate current step before proceeding
        // Skip credentials validation if already connected
        if (currentStep === 0 && !isConnected && !wizardData.serviceAccountEmail) {
            showError('Please upload your service account credentials first');
            return;
        }

        if (currentStep === 1 && !wizardData.spreadsheetUrl) {
            showError('Please enter your Google Sheets URL');
            return;
        }

        if (currentStep === 1) {
            // Check if at least one data type is enabled
            const hasEnabledType = Object.values(wizardData.sheetConfigs).some(config => config.enabled);
            if (!hasEnabledType) {
                showError('Please enable at least one data type to sync');
                return;
            }
        }

        if (currentStep < steps.length - 1) {
            setCurrentStep(currentStep + 1);
        }
    };

    const handleBack = () => {
        if (currentStep > 0) {
            setCurrentStep(currentStep - 1);
        }
    };

    const handleTestConnection = async () => {
        try {
            setLoading(true);

            // Pass the spreadsheet URL to test actual access
            const response = await api.testGoogleSheetsConnection(wizardData.spreadsheetUrl);

            if (response.success) {
                showSuccess('✅ Connection test successful! You have proper access to the spreadsheet.');
                return true;
            } else {
                throw new Error(response.message || 'Connection test failed');
            }
        } catch (err) {
            showError('Connection test failed: ' + err.message);
            return false;
        } finally {
            setLoading(false);
        }
    };

    const handleComplete = async () => {
        try {
            setLoading(true);

            // Save sheet configurations
            const configData = {
                spreadsheet_url: wizardData.spreadsheetUrl,
                sheet_configs: wizardData.sheetConfigs
            };

            const response = await api.saveGoogleSheetsConfig(configData);

            if (response.success) {
                showSuccess('🎉 Google Sheets setup completed successfully!');
                onComplete();
            } else {
                throw new Error(response.message || 'Failed to save configuration');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content wizard-modal" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>Google Sheets Setup Wizard</h3>
                    <button type="button" className="modal-close" onClick={onClose}>✕</button>
                </div>

                <div className="modal-body">
                    {/* Progress Steps */}
                    <div className="wizard-steps">
                        {steps.map((step, index) => (
                            <div key={index} className={`wizard-step ${index === currentStep ? 'active' : ''} ${index < currentStep ? 'completed' : ''}`}>
                                <div className="step-icon">{step.icon}</div>
                                <div className="step-title">{step.title}</div>
                            </div>
                        ))}
                    </div>

                    {/* Step Content */}
                    <div className="wizard-content">
                        {/* Step 1: Upload Credentials */}
                        {currentStep === 0 && (
                            <div className="wizard-step-content">
                                <h4>📁 Upload Service Account Credentials</h4>
                                <p>Upload your Google Service Account JSON file to authenticate with Google Sheets API.</p>

                                <div className="upload-area">
                                    <input
                                        type="file"
                                        ref={fileInputRef}
                                        onChange={handleFileUpload}
                                        accept=".json"
                                        style={{ display: 'none' }}
                                    />
                                    <div
                                        className={`upload-dropzone ${loading ? 'uploading' : ''}`}
                                        onClick={() => !loading && fileInputRef.current?.click()}
                                        onDragOver={(e) => {
                                            e.preventDefault();
                                            e.currentTarget.classList.add('drag-over');
                                        }}
                                        onDragLeave={(e) => {
                                            e.preventDefault();
                                            e.currentTarget.classList.remove('drag-over');
                                        }}
                                        onDrop={(e) => {
                                            e.preventDefault();
                                            e.currentTarget.classList.remove('drag-over');
                                            if (loading) return;

                                            const files = e.dataTransfer.files;
                                            if (files.length > 0) {
                                                const event = { target: { files: [files[0]] } };
                                                handleFileUpload(event);
                                            }
                                        }}
                                    >
                                        {loading ? (
                                            <>
                                                <div className="spinner"></div>
                                                <div className="upload-text">
                                                    <p><strong>Uploading credentials...</strong></p>
                                                </div>
                                            </>
                                        ) : (
                                            <>
                                                <div className="upload-icon">📁</div>
                                                <div className="upload-text">
                                                    <p><strong>Click to upload</strong> or drag and drop</p>
                                                    <p className="text-gray-600">JSON files only</p>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                </div>

                                {wizardData.serviceAccountEmail && (
                                    <div className="success-message">
                                        <div className="chip chip-success">✅ Credentials Uploaded</div>
                                        <p><strong>Service Account:</strong> {wizardData.serviceAccountEmail}</p>
                                    </div>
                                )}

                                <div className="help-section">
                                    <h5>Need help getting credentials?</h5>
                                    <ol>
                                        <li>Go to <a href="https://console.cloud.google.com/" target="_blank" rel="noopener noreferrer">Google Cloud Console</a></li>
                                        <li>Create or select a project</li>
                                        <li>Enable the Google Sheets API</li>
                                        <li>Create a Service Account</li>
                                        <li>Download the JSON key file</li>
                                    </ol>
                                </div>
                            </div>
                        )}

                        {/* Step 2: Configure Sheets */}
                        {currentStep === 1 && (
                            <div className="wizard-step-content">
                                <h4>📊 Configure Your Google Sheets</h4>
                                <p>Set up your Google Sheets URL and configure which data types to export.</p>

                                <div className="form-group">
                                    <label>Google Sheets URL</label>
                                    <input
                                        type="url"
                                        value={wizardData.spreadsheetUrl}
                                        onChange={(e) => {
                                            const url = e.target.value;
                                            setWizardData(prev => ({ ...prev, spreadsheetUrl: url }));

                                            // Validate Google Sheets URL format
                                            if (url && !url.includes('docs.google.com/spreadsheets')) {
                                                e.target.setCustomValidity('Please enter a valid Google Sheets URL');
                                            } else {
                                                e.target.setCustomValidity('');
                                            }
                                        }}
                                        placeholder="https://docs.google.com/spreadsheets/d/..."
                                        required
                                    />
                                    <div className="help-text">
                                        Copy the full URL of your Google Sheets document
                                    </div>
                                </div>

                                <div className="sheet-configs">
                                    <h5>Data Types to Export</h5>
                                    {Object.entries(wizardData.sheetConfigs).map(([type, config]) => (
                                        <div key={type} className="sheet-config-item">
                                            <div className="config-header">
                                                <label className="switch">
                                                    <input
                                                        type="checkbox"
                                                        checked={config.enabled}
                                                        onChange={(e) => setWizardData(prev => ({
                                                            ...prev,
                                                            sheetConfigs: {
                                                                ...prev.sheetConfigs,
                                                                [type]: { ...config, enabled: e.target.checked }
                                                            }
                                                        }))}
                                                    />
                                                    <span className="slider"></span>
                                                </label>
                                                <span className="config-label">{type.charAt(0).toUpperCase() + type.slice(1)} Data</span>
                                            </div>
                                            {config.enabled && (
                                                <div className="config-details">
                                                    <input
                                                        type="text"
                                                        value={config.tabName}
                                                        onChange={(e) => setWizardData(prev => ({
                                                            ...prev,
                                                            sheetConfigs: {
                                                                ...prev.sheetConfigs,
                                                                [type]: { ...config, tabName: e.target.value }
                                                            }
                                                        }))}
                                                        placeholder={`${type} tab name`}
                                                    />
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* Step 3: Grant Access */}
                        {currentStep === 2 && (
                            <div className="wizard-step-content">
                                <h4>🔑 Grant Access to Your Sheets</h4>
                                <p>Share your Google Sheets with the service account to allow data synchronization.</p>

                                <div className="access-instructions">
                                    <div className="instruction-step">
                                        <div className="step-number">1</div>
                                        <div className="step-content">
                                            <p><strong>Copy the service account email:</strong></p>
                                            <div className="copy-field">
                                                <input type="text" value={wizardData.serviceAccountEmail} readOnly />
                                                <button
                                                    className="btn btn-secondary btn-sm"
                                                    onClick={() => navigator.clipboard.writeText(wizardData.serviceAccountEmail)}
                                                >
                                                    📋 Copy
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="instruction-step">
                                        <div className="step-number">2</div>
                                        <div className="step-content">
                                            <p><strong>Open your Google Sheets and click "Share"</strong></p>
                                        </div>
                                    </div>

                                    <div className="instruction-step">
                                        <div className="step-number">3</div>
                                        <div className="step-content">
                                            <p><strong>Paste the service account email and give "Editor" permissions</strong></p>
                                        </div>
                                    </div>
                                </div>

                                {wizardData.spreadsheetUrl && (
                                    <div className="quick-access">
                                        <button
                                            className="btn btn-primary"
                                            onClick={() => window.open(wizardData.spreadsheetUrl, '_blank')}
                                        >
                                            🔗 Open Your Google Sheets
                                        </button>
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Step 4: Complete Setup */}
                        {currentStep === 3 && (
                            <div className="wizard-step-content">
                                <h4>✅ Complete Setup</h4>
                                <p>Review your configuration and complete the setup process.</p>

                                <div className="setup-summary">
                                    <div className="summary-item">
                                        <strong>Service Account:</strong> {wizardData.serviceAccountEmail}
                                    </div>
                                    <div className="summary-item">
                                        <strong>Spreadsheet:</strong> {wizardData.spreadsheetUrl}
                                    </div>
                                    <div className="summary-item">
                                        <strong>Enabled Data Types:</strong>
                                        <div className="enabled-types">
                                            {Object.entries(wizardData.sheetConfigs)
                                                .filter(([, config]) => config.enabled)
                                                .map(([type, config]) => (
                                                    <div key={type} className="chip chip-success">
                                                        {type.charAt(0).toUpperCase() + type.slice(1)} → {config.tabName}
                                                    </div>
                                                ))}
                                        </div>
                                    </div>
                                </div>

                                <div className="test-connection-section">
                                    <button
                                        className={`btn btn-secondary ${loading ? 'btn-loading' : ''}`}
                                        onClick={handleTestConnection}
                                        disabled={loading}
                                    >
                                        {loading ? (
                                            <>
                                                <div className="spinner"></div>
                                                Testing...
                                            </>
                                        ) : (
                                            '🔍 Test Connection'
                                        )}
                                    </button>
                                    <p className="text-gray-600">Test the connection before completing setup</p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <div className="modal-footer">
                    <div className="wizard-actions">
                        {currentStep > 0 && (
                            <button
                                className="btn btn-secondary"
                                onClick={handleBack}
                                disabled={loading}
                            >
                                ← Back
                            </button>
                        )}

                        {currentStep < steps.length - 1 ? (
                            <button
                                className="btn btn-primary"
                                onClick={handleNext}
                                disabled={loading || (currentStep === 0 && !isConnected && !wizardData.serviceAccountEmail) || (currentStep === 1 && !wizardData.spreadsheetUrl)}
                            >
                                Next →
                            </button>
                        ) : (
                            <button
                                className={`btn btn-success ${loading ? 'btn-loading' : ''}`}
                                onClick={handleComplete}
                                disabled={loading}
                            >
                                {loading ? (
                                    <>
                                        <div className="spinner"></div>
                                        Completing...
                                    </>
                                ) : (
                                    '🎉 Complete Setup'
                                )}
                            </button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Settings;