import React, { useState, useEffect } from 'react';

const Settings = () => {
    // console.log('Settings component loaded');
    // console.log('Window acb_firebase_config:', window.acb_firebase_config);
    
    const [firebaseConfig, setFirebaseConfig] = useState({
        apiKey: '',
        authDomain: '',
        projectId: '',
        storageBucket: '',
        messagingSenderId: '',
        appId: ''
    });
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState('');
    const [messageType, setMessageType] = useState('');

    useEffect(() => {
        // console.log('Settings useEffect triggered');
        // Load existing Firebase config
        const existingConfig = window.acb_firebase_config || {};
        // console.log('Existing config:', existingConfig);
        setFirebaseConfig({
            apiKey: existingConfig.apiKey || '',
            authDomain: existingConfig.authDomain || '',
            projectId: existingConfig.projectId || '',
            storageBucket: existingConfig.storageBucket || '',
            messagingSenderId: existingConfig.messagingSenderId || '',
            appId: existingConfig.appId || ''
        });
    }, []);

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFirebaseConfig(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setMessage('');

        try {
            // console.log('Submitting Firebase config:', firebaseConfig);
            // console.log('Nonce:', window.acb_firebase_nonce);
            // console.log('Ajax URL:', window.ajaxurl);
            
            const requestBody = new URLSearchParams({
                action: 'acb_save_firebase_config',
                nonce: window.acb_firebase_nonce,
                config: JSON.stringify(firebaseConfig)
            });
            
            // console.log('Request body:', requestBody.toString());
            
            const response = await fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: requestBody
            });

            // console.log('Response status:', response.status);
            // console.log('Response headers:', response.headers);
            const responseText = await response.text();
            // console.log('Response text:', responseText);
            // console.log('Response text length:', responseText.length);
            
            let data;
            try {
                data = JSON.parse(responseText);
                // console.log('Parsed response data:', data);
            } catch (parseError) {
                console.error('Failed to parse JSON response:', parseError);
                console.error('Raw response text:', responseText);
                setMessage('Invalid response from server: ' + responseText);
                setMessageType('error');
                return;
            }
            
            if (data.success) {
                setMessage('Firebase configuration saved successfully!');
                setMessageType('success');
            } else {
                setMessage(data.data || 'Failed to save configuration');
                setMessageType('error');
            }
        } catch (error) {
            console.error('Error saving configuration:', error);
            setMessage('Error saving configuration: ' + error.message);
            setMessageType('error');
        } finally {
            setLoading(false);
        }
    };

    const testConnection = async () => {
        if (!firebaseConfig.apiKey || !firebaseConfig.projectId) {
            setMessage('Please fill in the required fields first');
            setMessageType('error');
            return;
        }

        setLoading(true);
        setMessage('Testing Firebase connection...');

        try {
            const response = await fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'acb_test_firebase_connection',
                    nonce: window.acb_firebase_nonce,
                    config: JSON.stringify(firebaseConfig)
                })
            });

            const data = await response.json();
            
            if (data.success) {
                setMessage(data.data || 'Firebase connection successful! Configuration is valid.');
                setMessageType('success');
            } else {
                setMessage(data.data || 'Firebase connection failed');
                setMessageType('error');
            }
        } catch (error) {
            setMessage('Error testing connection: ' + error.message);
            setMessageType('error');
        } finally {
            setLoading(false);
        }
    };

    const firestoreRules = `rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Allow users to read and write their own data
    match /users/{userId} {
      allow read, write: if request.auth != null;
    }
    
    // Allow users to read and write chat messages
    match /chats/{chatId}/messages/{messageId} {
      allow read, write: if request.auth != null;
    }
    
    // Allow users to read and write chat metadata
    match /chats/{chatId} {
      allow read, write: if request.auth != null;
    }
  }
}`;

    const firebaseConfigExample = `const firebaseConfig = {
  apiKey: "AIzaSyC...",
  authDomain: "your-project.firebaseapp.com",
  projectId: "your-project-id",
  storageBucket: "your-project.appspot.com",
  messagingSenderId: "123456789",
  appId: "1:123456789:web:abc123"
};`;

    return (
        <div className="settings-container">
            <div className="settings-header">
                <h1 className="settings-title">Firebase Configuration</h1>
                <p className="settings-description">Configure your Firebase project settings to enable real-time chat functionality.</p>
            </div>

            <div className="config-form">
                <div className="form-fields">
                    <div className="field-group">
                        <label htmlFor="apiKey" className="field-label">
                            API Key *
                        </label>
                        <input
                            type="text"
                            id="apiKey"
                            name="apiKey"
                            value={firebaseConfig.apiKey}
                            onChange={handleInputChange}
                            placeholder="AIzaSyC..."
                            required
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase project API key</small>
                    </div>

                    <div className="field-group">
                        <label htmlFor="authDomain" className="field-label">
                            Auth Domain *
                        </label>
                        <input
                            type="text"
                            id="authDomain"
                            name="authDomain"
                            value={firebaseConfig.authDomain}
                            onChange={handleInputChange}
                            placeholder="your-project.firebaseapp.com"
                            required
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase project auth domain</small>
                    </div>

                    <div className="field-group">
                        <label htmlFor="projectId" className="field-label">
                            Project ID *
                        </label>
                        <input
                            type="text"
                            id="projectId"
                            name="projectId"
                            value={firebaseConfig.projectId}
                            onChange={handleInputChange}
                            placeholder="your-project-id"
                            required
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase project ID</small>
                    </div>

                    <div className="field-group">
                        <label htmlFor="storageBucket" className="field-label">
                            Storage Bucket
                        </label>
                        <input
                            type="text"
                            id="storageBucket"
                            name="storageBucket"
                            value={firebaseConfig.storageBucket}
                            onChange={handleInputChange}
                            placeholder="your-project.appspot.com"
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase storage bucket (optional)</small>
                    </div>

                    <div className="field-group">
                        <label htmlFor="messagingSenderId" className="field-label">
                            Messaging Sender ID
                        </label>
                        <input
                            type="text"
                            id="messagingSenderId"
                            name="messagingSenderId"
                            value={firebaseConfig.messagingSenderId}
                            onChange={handleInputChange}
                            placeholder="123456789"
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase messaging sender ID (optional)</small>
                    </div>

                    <div className="field-group">
                        <label htmlFor="appId" className="field-label">
                            App ID
                        </label>
                        <input
                            type="text"
                            id="appId"
                            name="appId"
                            value={firebaseConfig.appId}
                            onChange={handleInputChange}
                            placeholder="1:123456789:web:abc123"
                            className="field-input"
                        />
                        <small className="field-help">Your Firebase app ID (optional)</small>
                    </div>

                    {message && (
                        <div className={`message-alert ${messageType === 'success' ? 'message-success' : 'message-error'}`}>
                            {message}
                        </div>
                    )}

                    <div className="button-group">
                        <button
                            type="button"
                            onClick={testConnection}
                            disabled={loading}
                            className="btn btn-secondary"
                        >
                            {loading ? 'Testing...' : 'Test Connection'}
                        </button>
                        <button
                            type="button"
                            onClick={handleSubmit}
                            disabled={loading}
                            className="btn btn-primary"
                        >
                            {loading ? 'Saving...' : 'Save Configuration'}
                        </button>
                    </div>
                </div>
            </div>

            {/* Firebase Setup Guide */}
            <div className="setup-guide">
                <h2 className="setup-guide-title">📋 Complete Firebase Setup Guide</h2>
                
                <div className="setup-step">
                    <h3 className="step-title">Step 1: Create Firebase Project</h3>
                    <ol className="step-list">
                        <li>Go to <a href="https://console.firebase.google.com/" target="_blank" rel="noopener noreferrer" className="external-link">Firebase Console</a></li>
                        <li>Click "Create a project" or "Add project"</li>
                        <li>Enter a project name (e.g., "admin-chat-box")</li>
                        <li>Choose whether to enable Google Analytics (optional)</li>
                        <li>Click "Create project"</li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 2: Enable Authentication</h3>
                    <ol className="step-list">
                        <li>In your Firebase project, go to "Authentication" in the left sidebar</li>
                        <li>Click "Get started"</li>
                        <li>Go to "Sign-in method" tab</li>
                        <li>Enable "Google" provider:
                            <ul className="sub-step-list">
                                <li>Click on "Google"</li>
                                <li>Toggle "Enable"</li>
                                <li>Add your support email</li>
                                <li>Click "Save"</li>
                            </ul>
                        </li>
                        <li>Enable "Email/Password" provider:
                            <ul className="sub-step-list">
                                <li>Click on "Email/Password"</li>
                                <li>Toggle "Enable"</li>
                                <li>Toggle "Email link (passwordless sign-in)" if desired</li>
                                <li>Click "Save"</li>
                            </ul>
                        </li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 3: Set Up Firestore Database</h3>
                    <ol className="step-list">
                        <li>In your Firebase project, go to "Firestore Database" in the left sidebar</li>
                        <li>Click "Create database"</li>
                        <li>Choose "Start in test mode" (for development)</li>
                        <li>Select a location closest to your users</li>
                        <li>Click "Done"</li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 4: Configure Firestore Security Rules</h3>
                    <ol className="step-list">
                        <li>In Firestore Database, go to "Rules" tab</li>
                        <li>Replace the default rules with:</li>
                        <pre className="code-block">
                            {firestoreRules}
                        </pre>
                        <li>Click "Publish"</li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 5: Get Firebase Configuration</h3>
                    <ol className="step-list">
                        <li>In your Firebase project, click the gear icon ⚙️ next to "Project Overview"</li>
                        <li>Select "Project settings"</li>
                        <li>Scroll down to "Your apps" section</li>
                        <li>Click the web icon (&lt;/&gt;) to add a web app</li>
                        <li>Enter an app nickname (e.g., "Admin Chat Box")</li>
                        <li>Click "Register app"</li>
                        <li>Copy the configuration object that looks like this:</li>
                        <pre className="code-block">
                            {firebaseConfigExample}
                        </pre>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 6: Configure OAuth Consent Screen (for Google Sign-in)</h3>
                    <ol className="step-list">
                        <li>Go to <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer" className="external-link">Google Cloud Console</a></li>
                        <li>Select your Firebase project</li>
                        <li>Go to "APIs & Services" → "OAuth consent screen"</li>
                        <li>Choose "External" user type</li>
                        <li>Fill in the required information:
                            <ul className="sub-step-list">
                                <li>App name: Your app name</li>
                                <li>User support email: Your email</li>
                                <li>Developer contact information: Your email</li>
                            </ul>
                        </li>
                        <li>Add your domain to "Authorized domains"</li>
                        <li>Click "Save and Continue" through all steps</li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">Step 7: Test Your Setup</h3>
                    <ol className="step-list">
                        <li>Enter your Firebase configuration below</li>
                        <li>Click "Test Connection" to verify everything works</li>
                        <li>If successful, click "Save Configuration"</li>
                        <li>Go to Admin Chat Box → Dashboard to test the chat</li>
                    </ol>
                </div>

                <div className="setup-step">
                    <h3 className="step-title">🔧 Troubleshooting</h3>
                    <ul className="troubleshooting-list">
                        <li><strong>Authentication errors:</strong> Make sure Google provider is enabled and OAuth consent screen is configured</li>
                        <li><strong>Firestore errors:</strong> Check that Firestore is created and rules are published</li>
                        <li><strong>Users not showing:</strong> Users need to sign in at least once to appear in the chat</li>
                        <li><strong>Search not working:</strong> Use the "Sync Firebase Auth Users" button in the chat to add existing users</li>
                    </ul>
                </div>
            </div>

        
            <div className="info-box">
                <h3 className="info-title">How to get Firebase Configuration</h3>
                <ol className="info-list">
                    <li>Go to <a href="https://console.firebase.google.com/" target="_blank" rel="noopener noreferrer" className="external-link">Firebase Console</a></li>
                    <li>Create a new project or select an existing one</li>
                    <li>Click on the gear icon (⚙️) next to "Project Overview"</li>
                    <li>Select "Project settings"</li>
                    <li>Scroll down to "Your apps" section</li>
                    <li>Click "Add app" and choose "Web" (&lt;/&gt;)</li>
                    <li>Register your app and copy the configuration</li>
                    <li>Paste the values in the form above</li>
                </ol>
                
                <div className="note-box">
                    <strong className="note-title">Note:</strong>
                    <span className="note-text"> Make sure to enable Authentication and Firestore in your Firebase project:</span>
                    <ul className="note-list">
                        <li>Go to Authentication → Sign-in method → Enable Google and Email/Password</li>
                        <li>Go to Firestore Database → Create database → Start in test mode</li>
                    </ul>
                </div>
            </div>
        </div>
    );
};

export default Settings;