import React, { useState, useEffect } from 'react';
import Settings from "./Settings";
import { getNonce, getConfig, adminAjax } from './Helpers';
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, collection, getDocs, query, where } from 'firebase/firestore';


// Add this component to handle image loading issues
const SafeImage = ({ src, alt, className, fallbackSrc }) => {
    const [imgSrc, setImgSrc] = useState(src);
    const [hasError, setHasError] = useState(false);

    useEffect(() => {
        // Check if it's a Google user content URL that needs proxying
        if (src && src.includes('googleusercontent.com')) {
            const proxyUrl = `${adminAjax()}?action=acb_proxy_image&url=${encodeURIComponent(src)}&nonce=${getNonce()}`;
            setImgSrc(proxyUrl);
        } else {
            setImgSrc(src);
        }
        setHasError(false);
    }, [src]);

    const handleError = () => {
        if (!hasError) {
            setHasError(true);
            // Try the original URL first if proxy failed
            if (imgSrc.includes('admin-ajax.php')) {
                setImgSrc(src);
            } else {
                // If original also failed, use fallback
                setImgSrc(fallbackSrc || 'https://static.vecteezy.com/system/resources/previews/022/059/000/non_2x/no-image-available-icon-vector.jpg');
            }
        }
    };

    const handleLoad = () => {
        setHasError(false);
    };

    return (
        <img 
            src={imgSrc}
            alt={alt}
            className={className}
            referrerPolicy="no-referrer"
            crossOrigin="anonymous"
            onError={handleError}
            onLoad={handleLoad}
            loading="lazy"
        />
    );
}

const Users = () => {
    const [activeTab, setActiveTab] = useState('configuration');
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [message, setMessage] = useState({ type: '', text: '' });
    
    // Support System Settings
    const [supportSystemEnabled, setSupportSystemEnabled] = useState(false);
    const [savingSettings, setSavingSettings] = useState(false);
    
    // Widget Settings
    const [widgetSettings, setWidgetSettings] = useState({
        frontend_widget_enabled: true,
        widget_position: 'bottom-right',
        widget_title: 'Chat Support',
        widget_description: 'Need help? Chat with our team!',
        widget_primary_color: '#5A5EB9',
        widget_show_on_pages: 'all',
        widget_exclude_pages: ''
    });
    const [savingWidgetSettings, setSavingWidgetSettings] = useState(false);

    // Firebase states
    const [firebaseApp, setFirebaseApp] = useState(null);
    const [auth, setAuth] = useState(null);
    const [db, setDb] = useState(null);
    const [firebaseUsers, setFirebaseUsers] = useState([]);
    const [syncingUsers, setSyncingUsers] = useState(false);

    // Initialize Firebase
    useEffect(() => {
        const config = getConfig();
        if (config && config.apiKey) {
            try {
                const app = initializeApp(config);
                const firebaseAuth = getAuth(app);
                const firestoreDb = getFirestore(app);
                setFirebaseApp(app);
                setAuth(firebaseAuth);
                setDb(firestoreDb);
            } catch (error) {
                console.error('Firebase initialization error:', error);
                setError('Failed to initialize Firebase: ' + error.message);
            }
        } else {
            setError('Firebase configuration not found');
        }
    }, []);

    // Load initial data
    useEffect(() => {
        loadSupportSettings();
        loadWidgetSettings();
        loadUsers();
    }, []);

    // Load Firebase users when Firebase is ready
    useEffect(() => {
        if (db) {
            loadFirebaseUsers();
        }
    }, [db]);

    const loadSupportSettings = async () => {
        try {
            
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_get_support_settings',
                    nonce: getNonce()
                })
            });
            const data = await response.json();
            if (data.success) {
                setSupportSystemEnabled(data.data.support_system_enabled === true || data.data.support_system_enabled === '1' || data.data.support_system_enabled === 1);
            }
        } catch (error) {
            console.error('Error loading support settings:', error);
        }
    };

    const loadWidgetSettings = async () => {
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_get_widget_settings',
                    nonce: getNonce()
                })
            });
            const data = await response.json();
            if (data.success) {
                const settings = data.data.widget_settings;
                settings.frontend_widget_enabled = settings.frontend_widget_enabled === true || settings.frontend_widget_enabled === '1' || settings.frontend_widget_enabled === 1;
                setWidgetSettings(settings);
            }
        } catch (error) {
            console.error('Error loading widget settings:', error);
        }
    };

    const loadUsers = async () => {
        setLoading(true);
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_get_all_users',
                    nonce: getNonce()
                })
            });
            const data = await response.json();
            if (data.success) {
                setUsers(data.data.users);
                setError(null);
            } else {
                setError(data.data || 'Failed to load users');
            }
        } catch (error) {
            console.error('Error loading users:', error);
            setError('Error loading users: ' + error.message);
        } finally {
            setLoading(false);
        }
    };

    const loadFirebaseUsers = async () => {
        if (!db) return;
        try {
            const usersQuery = query(collection(db, 'users'));
            const querySnapshot = await getDocs(usersQuery);
            const fbUsers = [];
            querySnapshot.forEach((doc) => {
                const userData = { id: doc.id, ...doc.data() };
                if (!userData.uid.startsWith('test_user_')) {
                    fbUsers.push(userData);
                }
            });
            setFirebaseUsers(fbUsers);
        } catch (error) {
            console.error('Error loading Firebase users:', error);
        }
    };

    const saveSupportSettings = async () => {
        setSavingSettings(true);
        setMessage({ type: '', text: '' });
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_save_support_settings',
                    nonce: getNonce(),
                    support_system_enabled: supportSystemEnabled
                })
            });
            const data = await response.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Support settings saved successfully!' });
            } else {
                setMessage({ type: 'error', text: 'Error: ' + data.data });
            }
        } catch (error) {
            setMessage({ type: 'error', text: 'Error saving settings: ' + error.message });
        } finally {
            setSavingSettings(false);
        }
    };

    const saveWidgetSettings = async () => {
        setSavingWidgetSettings(true);
        setMessage({ type: '', text: '' });
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_save_widget_settings',
                    nonce: getNonce(),
                    ...widgetSettings
                })
            });
            const data = await response.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Widget settings saved successfully!' });
            } else {
                setMessage({ type: 'error', text: 'Error: ' + data.data });
            }
        } catch (error) {
            setMessage({ type: 'error', text: 'Error saving widget settings: ' + error.message });
        } finally {
            setSavingWidgetSettings(false);
        }
    };

    const syncFirebaseUsers = async () => {
        if (!db || firebaseUsers.length === 0) {
            setMessage({ type: 'error', text: 'No Firebase users found to sync' });
            return;
        }
        setSyncingUsers(true);
        setMessage({ type: '', text: '' });
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_sync_firebase_users',
                    nonce: getNonce(),
                    firebase_users: JSON.stringify(firebaseUsers)
                })
            });
            const data = await response.json();
            if (data.success) {
                setMessage({
                    type: 'success',
                    text: data.data.message + (data.data.errors.length > 0 ? ` (${data.data.errors.length} errors)` : '')
                });
                await loadUsers();
            } else {
                setMessage({ type: 'error', text: 'Error: ' + data.data });
            }
        } catch (error) {
            setMessage({ type: 'error', text: 'Error syncing users: ' + error.message });
        } finally {
            setSyncingUsers(false);
        }
    };

    const toggleUserAdmin = async (userId, currentRole) => {
        const newRole = currentRole === 'admin' ? 'regular' : 'admin';
        try {
            const response = await fetch(adminAjax() || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'acb_toggle_user_agent',
                    nonce: getNonce(),
                    user_id: userId,
                    new_role: newRole
                })
            });
            const data = await response.json();
            if (data.success) {
                setUsers(prevUsers =>
                    prevUsers.map(user =>
                        user.id === userId ? { ...user, is_admin: newRole === 'admin' } : user
                    )
                );
                setMessage({ type: 'success', text: 'User role updated successfully!' });
            } else {
                setMessage({ type: 'error', text: 'Error: ' + data.data });
            }
        } catch (error) {
            setMessage({ type: 'error', text: 'Error updating user role: ' + error.message });
        }
    };

    const handleWidgetSettingChange = (key, value) => {
        setWidgetSettings(prev => ({ ...prev, [key]: value }));
    };

    const tabs = [
        { id: 'users', label: 'Users Management', icon: '👥' },
        { id: 'configuration', label: 'Configuration', icon: '🔥' },
        { id: 'support', label: 'Support Settings', icon: '🛠️' },
        { id: 'widget', label: 'Widget Settings', icon: '💬' },
        { id: 'sync', label: 'Sync Users', icon: '🔄' }
    ];

   

    const renderUsersTab = () => (
        <div className="users-tab-content">
            <div className="tab-header">
                <h2>Chat Users Management</h2>
                <p>Manage chat user roles and permissions. Admin users can see and chat with all users.</p>
                <div className="users-stats">
                    <div className="stat-card">
                        <span className="stat-number">{users.length}</span>
                        <span className="stat-label">Total Users</span>
                    </div>
                    <div className="stat-card">
                        <span className="stat-number">{users.filter(u => u.is_admin).length}</span>
                        <span className="stat-label">Admin/Agent Users</span>
                    </div>
                    <div className="stat-card">
                        <span className="stat-number">{users.filter(u => u.is_online).length}</span>
                        <span className="stat-label">Online Now</span>
                    </div>
                </div>
            </div>

            {error ? (
                <div className="error-message">
                    <strong>Error:</strong> {error}
                </div>
            ) : users.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-icon">👥</div>
                    <h3>No Users Found</h3>
                    <p>Users will appear here after they sign up and use the chat system.</p>
                </div>
            ) : (
                <div className="users-table-container">
                    <table className="users-table">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Contact</th>
                                <th>Status</th>
                                <th>Role</th>
                                <th>Last Seen</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {users.map((user) => (
                                <tr key={user.id}>
                                    <td>
                                        <div className="user-info">
                                            {/* <img
                                                src={user.user_avatar || 'https://static.vecteezy.com/system/resources/previews/022/059/000/non_2x/no-image-available-icon-vector.jpg'}
                                                alt={user.user_name}
                                                className="user-avatar"
                                            /> */}
                                            <SafeImage 
                                                    src={user.user_avatar} 
                                                    alt={user.user_name || user.email}  
                                                    className="user-avatar"
                                                    fallbackSrc="https://static.vecteezy.com/system/resources/previews/022/059/000/non_2x/no-image-available-icon-vector.jpg"
                                                />
                                            <span className="user-name">{user.user_name}</span>
                                        </div>
                                    </td>
                                    <td>
                                        <div className="user-contact">
                                            <span className="user-email">{user.user_email}</span>
                                        </div>
                                    </td>
                                    <td>
                                        <span className={`status-badge ${user.is_online ? 'online' : 'offline'}`}>
                                            <span className="status-dot"></span>
                                            {user.is_online ? 'Online' : 'Offline'}
                                        </span>
                                    </td>
                                    <td>
                                        <span className={`role-badge ${user.is_admin ? 'admin' : 'regular'}`}>
                                            {user.is_admin ? 'Agent' : 'Regular'}
                                        </span>
                                    </td>
                                    <td>
                                        <span className="last-seen">{user.formatted_last_seen}</span>
                                    </td>
                                    <td>
                                        <button
                                            type="button"
                                            onClick={() => toggleUserAdmin(user.id, user.is_admin ? 'admin' : 'regular')}
                                            className={`action-btn ${user.is_admin ? 'remove-admin' : 'make-admin'}`}
                                        >
                                            {user.is_admin ? 'Remove Agent' : 'Make Agent'}
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );

     const renderConfigurationTab = () => (
        <div className="users-tab-content">
            <div className="tab-header">
                <h2>Firebase Configuration</h2>
                <p>Configure your Firebase project settings to enable real-time chat functionality.</p>
                <div className="users-stats">
                    <Settings />
                </div>
            </div>

            
        </div>
    );

    const renderSupportTab = () => (
        <div className="support-tab-content">
            <div className="tab-header">
                <h2>Support System Settings</h2>
                <p>Configure how the chat system handles user interactions and permissions.</p>
            </div>

            <div className="settings-card">
                <div className="setting-item">
                    <div className="setting-info">
                        <h3>Support System Mode</h3>
                        <p>When enabled, regular users can only chat with agent only. When disabled, all users can chat with everyone.</p>
                    </div>
                    <div className="setting-control">
                        <label className="toggle-switch">
                            <input
                                type="checkbox"
                                checked={supportSystemEnabled}
                                onChange={(e) => setSupportSystemEnabled(e.target.checked)}
                            />
                            <span className="toggle-slider"></span>
                        </label>
                    </div>
                </div>
                
                <div className="setting-actions">
                    <button
                        type="button"
                        onClick={saveSupportSettings}
                        disabled={savingSettings}
                        className="btn btn-primary"
                    >
                        {savingSettings ? 'Saving...' : 'Save Support Settings'}
                    </button>
                </div>
            </div>
        </div>
    );

    const renderWidgetTab = () => (
        <div className="widget-tab-content">
            <div className="tab-header">
                <h2>Frontend Widget Settings</h2>
                <p>Configure the chat widget appearance and behavior on your website.</p>
            </div>

            <div className="settings-grid">
                <div className="settings-card">
                    <h3>Widget Visibility</h3>
                    <div className="setting-item">
                        <div className="setting-info">
                            <label>Enable Frontend Widget</label>
                            <p>Show/hide the chat widget on your website frontend</p>
                        </div>
                        <div className="setting-control">
                            <label className="toggle-switch">
                                <input
                                    type="checkbox"
                                    checked={widgetSettings.frontend_widget_enabled}
                                    onChange={(e) => handleWidgetSettingChange('frontend_widget_enabled', e.target.checked)}
                                />
                                <span className="toggle-slider"></span>
                            </label>
                        </div>
                    </div>
                </div>

                <div className="settings-card">
                    <h3>Widget Position</h3>
                    <div className="setting-item">
                        <div className="setting-info">
                            <label>Position</label>
                            <p>Choose where the chat widget appears</p>
                        </div>
                        <div className="setting-control">
                            <select
                                value={widgetSettings.widget_position}
                                onChange={(e) => handleWidgetSettingChange('widget_position', e.target.value)}
                                className="form-select"
                            >
                                <option value="bottom-right">Bottom Right</option>
                                <option value="bottom-left">Bottom Left</option>
                                <option value="top-right">Top Right</option>
                                <option value="top-left">Top Left</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div className="settings-card">
                    <h3>Widget Content</h3>
                    <div className="setting-item">
                        <div className="setting-info">
                            <label>Widget Title</label>
                            <p>Title shown in the chat widget header</p>
                        </div>
                        <div className="setting-control">
                            <input
                                type="text"
                                value={widgetSettings.widget_title}
                                onChange={(e) => handleWidgetSettingChange('widget_title', e.target.value)}
                                className="form-input"
                                placeholder="Chat Support"
                            />
                        </div>
                    </div>
                    <div className="setting-item">
                        <div className="setting-info">
                            <label>Widget Description</label>
                            <p>Welcome message shown to users</p>
                        </div>
                        <div className="setting-control">
                            <textarea
                                value={widgetSettings.widget_description}
                                onChange={(e) => handleWidgetSettingChange('widget_description', e.target.value)}
                                className="form-textarea"
                                placeholder="Need help? Chat with our team!"
                                rows="3"
                            />
                        </div>
                    </div>
                </div>

                <div className="settings-card">
                    <h3>Widget Styling</h3>
                    <div className="setting-item">
                        <div className="setting-info">
                            <label>Primary Color</label>
                            <p>Primary color for the widget theme</p>
                        </div>
                        <div className="setting-control">
                            <div className="color-picker">
                                <input
                                    type="color"
                                    value={widgetSettings.widget_primary_color}
                                    onChange={(e) => handleWidgetSettingChange('widget_primary_color', e.target.value)}
                                    className="color-input"
                                />
                                <input
                                    type="text"
                                    value={widgetSettings.widget_primary_color}
                                    onChange={(e) => handleWidgetSettingChange('widget_primary_color', e.target.value)}
                                    className="color-text"
                                    placeholder="#5A5EB9"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="shortcode-section">
                <h3>Shortcode Usage</h3>
                <p>You can place chat widgets anywhere on your site using these shortcodes:</p>
                <div className="shortcode-examples">
                    <div className="shortcode-example">
                        <strong>Basic Usage:</strong>
                        <code>[acb_chat_widget]</code>
                    </div>
                    <div className="shortcode-example">
                        <strong>Custom Position:</strong>
                        <code>[acb_chat_widget position="bottom-left"]</code>
                    </div>
                    <div className="shortcode-example">
                        <strong>Custom Title & Color:</strong>
                        <code>[acb_chat_widget title="Help Desk" color="#ff6b6b"]</code>
                    </div>
                    <div className="shortcode-example">
                        <strong>Inline Widget:</strong>
                        <code>[acb_chat_widget position="inline"]</code>
                    </div>
                </div>
            </div>

            <div className="setting-actions">
                <button
                    type="button"
                    onClick={saveWidgetSettings}
                    disabled={savingWidgetSettings}
                    className="btn btn-primary"
                >
                    {savingWidgetSettings ? 'Saving...' : 'Save Widget Settings'}
                </button>
            </div>
        </div>
    );

    const renderSyncTab = () => (
        <div className="sync-tab-content">
            <div className="tab-header">
                <h2>Sync Firebase Users</h2>
                <p>Import users from Firebase to WordPress database for proper chat functionality.</p>
            </div>

            <div className="sync-stats">
                <div className="stat-card firebase">
                    {/* <div className="stat-icon">🔥</div> */}
                    <div className="stat-info">
                        <span className="stat-number">{firebaseUsers.length}</span>
                        <span className="stat-label">Firebase Users</span>
                    </div>
                </div>
                <div className="stat-card wordpress">
                    {/* <div className="stat-icon">📊</div> */}
                    <div className="stat-info">
                        <span className="stat-number">{users.length}</span>
                        <span className="stat-label">WordPress Users</span>
                    </div>
                </div>
            </div>

            <div className="sync-info">
                <div className="info-card">
                    <h3>About User Synchronization</h3>
                    <p>If you have users in Firebase that are not showing in the chat users list, use the sync function to import them into the WordPress database. This ensures all users can properly use the chat system.</p>
                    <ul>
                        <li>Syncs user profiles and authentication data</li>
                        <li>Maintains user roles and permissions</li>
                        <li>Updates existing users with new information</li>
                        <li>Excludes test users from synchronization</li>
                    </ul>
                </div>
            </div>

            <div className="sync-actions">
                <button
                    type="button"
                    onClick={syncFirebaseUsers}
                    disabled={syncingUsers || firebaseUsers.length === 0}
                    className="btn btn-primary btn-large"
                >
                    {syncingUsers ? 'Syncing...' : `Sync ${firebaseUsers.length} Firebase Users`}
                </button>
            </div>
        </div>
    );

    if (loading) {
        return (
            <div className="loading-container">
                <div className="spinner"></div>
                <p>Loading...</p>
            </div>
        );
    }

    return (
        <div className="users-management-container">
            <div className="page-header">
                <h1>Chat Users Management</h1>
                <p>Manage your chat system users, settings, and synchronization</p>
            </div>

            {message.text && (
                <div className={`message-alert ${message.type}`}>
                    <div className="message-content">
                        {message.text}
                    </div>
                </div>
            )}

            <div className="tabs-container">
                <div className="tabs-nav">
                    {tabs.map(tab => (
                        <button
                            key={tab.id}
                            type="button"
                            className={`tab-button ${activeTab === tab.id ? 'active' : ''}`}
                            onClick={() => setActiveTab(tab.id)}
                        >
                            <span className="tab-icon">{tab.icon}</span>
                            <span className="tab-label">{tab.label}</span>
                        </button>
                    ))}
                </div>

                <div className="tabs-content">
                    {activeTab === 'users' && renderUsersTab()}
                    {activeTab === 'configuration' && renderConfigurationTab()}
                    {activeTab === 'support' && renderSupportTab()}
                    {activeTab === 'widget' && renderWidgetTab()}
                    {activeTab === 'sync' && renderSyncTab()}
                </div>
            </div>
        </div>
    );
};

export default Users;