import { successIcon, errorIcon, closeIcon } from './icons.js';

document.addEventListener('DOMContentLoaded', function() {
    const logoutForm = document.getElementById('logoutF');
    if (logoutForm) {
        logoutForm.addEventListener('submit', async function(e) {
            e.preventDefault(); // Prevent the default form submission

            const formData = new FormData();
            formData.append('action', 'cybreed_ajax_logout');
            formData.append('nonce', logoutForm.querySelector('input[name="cybreed_logout_nonce"]').value);

            try {
                const response = await fetch(ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
                });
                
                const data = await response.json();
                
                if (!data.success) {
                    throw new Error(data.message || 'Logout failed');
                }
                
                showToast('Logged out successfully', 'success');
                
                // Redirect after showing the toast
                setTimeout(() => {
                    const redirectTo = logoutForm.querySelector('input[name="redirect_to"]').value;
                    window.location.href = redirectTo;
                }, 1000);
            } catch (error) {
                showToast(error.message || 'An error occurred during logout', 'error');
            }
        });
    }
    // Create toast container if it doesn't exist
    let toastContainer = document.querySelector('.cybreed-toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'cybreed-toast-container';
        document.body.appendChild(toastContainer);
    }

    // Toast notification function
    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `cybreed-toast ${type}-cybreed`;
        const icon = type === 'success' ? successIcon : errorIcon;
        
        toast.innerHTML = `
            <span class="cybreed-toast-icon">${icon}</span>
            <div class="cybreed-toast-content">${message}</div>
            <button class="cybreed-toast-close" aria-label="Close">${closeIcon}</button>
        `;
        
        toastContainer.appendChild(toast);
        
        // Trigger reflow for animation
        toast.offsetHeight;
        
        // Show toast
        setTimeout(() => toast.classList.add('show'), 10);
        
        // Auto remove after 5 seconds
        const timeout = setTimeout(() => {
            removeToast(toast);
        }, 3600);
        
        // Close button handler
        const closeBtn = toast.querySelector('.cybreed-toast-close');
        closeBtn.addEventListener('click', () => {
            clearTimeout(timeout);
            removeToast(toast);
        });
    }
    
    function removeToast(toast) {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }

    const loginCard = document.querySelector('.cybreed-login-card');
    const loginForm = document.querySelector('.cybreed-login-form');
    const dashboardWrapper = document.querySelector('.cybreed-dashboard-inner-wrapper');

    // Only handle login form related code if the form exists
    if (loginForm) {
        // Add close button to the form if it doesn't exist
        if (!loginForm.querySelector('.close-button')) {
            const closeButton = document.createElement('button');
            closeButton.className = 'close-button';
            closeButton.innerHTML = '×';
            loginForm.insertBefore(closeButton, loginForm.firstChild);
        }

        function toggleLoginForm() {
            loginForm.classList.toggle('active');
            dashboardWrapper.classList.toggle('blur');
        }

        // Show login form when clicking the login card
        if (loginCard) {
            loginCard.addEventListener('click', toggleLoginForm);
        }

        // Close form when clicking the close button
        const closeButton = loginForm.querySelector('.close-button');
        if (closeButton) {
            closeButton.addEventListener('click', function(e) {
                e.preventDefault();
                toggleLoginForm();
            });
        }

        // Close form when clicking outside
        document.addEventListener('click', function(e) {
            if (loginForm.classList.contains('active') && 
                !loginForm.contains(e.target) && 
                !loginCard.contains(e.target)) {
                toggleLoginForm();
            }
        });

        // Prevent form close when clicking inside the form
        loginForm.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // Handle AJAX login
        const loginFormElement = loginForm.querySelector('form');
        if (loginFormElement) {
            loginFormElement.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const email = this.querySelector('input[name="email"]').value;
                const password = this.querySelector('input[name="password"]').value;
                const nonce = this.querySelector('#cybreed_login_nonce').value;
                
                // Disable form while processing
                const submitButton = this.querySelector('input[type="submit"]');
                const originalButtonText = submitButton.value;
                submitButton.value = 'Signing in...';
                submitButton.disabled = true;
                
                // Clear previous messages
                const existingMessage = loginForm.querySelector('.login-message');
                if (existingMessage) {
                    existingMessage.remove();
                }

                // Create FormData object
                const formData = new FormData();
                formData.append('action', 'cybreed_ajax_login');
                formData.append('email', email);
                formData.append('password', password);
                formData.append('nonce', nonce);

                fetch(ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    showToast(data.message, data.success ? 'success' : 'error');
                    
                    if (!data.success) {
                        loginForm.classList.add('error-cybreed');
                    } else {
                        loginForm.classList.remove('error-cybreed');
                    }
                    
                    if (data.success) {
                        // Reload page after successful login
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        // Reset button if login failed
                        submitButton.value = originalButtonText;
                        submitButton.disabled = false;
                    }
                })
                .catch(error => {
                    loginForm.classList.add('error-cybreed');
                    showToast('An error occurred. Please try again.', 'error');
                    
                    submitButton.value = originalButtonText;
                    submitButton.disabled = false;
                });
            });
        }

        // Remove error class when starting to type in inputs
        const inputs = loginForm.querySelectorAll('input[type="email"], input[type="password"]');
        inputs.forEach(input => {
            input.addEventListener('input', () => {
                loginForm.classList.remove('error-cybreed');
            });
        });
    }

    const orgSelect = document.querySelector('select[name="organisation_id"]');
    const chatSelect = document.querySelector('select[name="chat_id"]');
    const settingsForm = document.querySelector('.cybreed-settings-form');
    const settingsNonce = document.querySelector('#cybreed_settings_nonce');

    // Function to update chat select options
    function updateChatSelect(chats) {
        if (!chatSelect) return;
        
        // Clear existing options
        while (chatSelect.firstChild) {
            chatSelect.removeChild(chatSelect.firstChild);
        }
        
        // Add default option
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = 'Select a Chat';
        chatSelect.appendChild(defaultOption);
        
        // Add chat options
        if (chats && chats.length > 0) {
            chats.forEach(chat => {
                const option = document.createElement('option');
                option.value = chat.uuid;
                option.textContent = chat.name;
                chatSelect.appendChild(option);
            });
        } else {
            const noChatsOption = document.createElement('option');
            noChatsOption.value = '';
            noChatsOption.textContent = 'No chats available';
            noChatsOption.disabled = true;
            chatSelect.appendChild(noChatsOption);
        }
    }

    // Handle organization change
    if (orgSelect) {
        orgSelect.addEventListener('change', async function() {
            try {
                if (!this.value) {
                    updateChatSelect([]);
                    return;
                }

                const formData = new FormData();
                formData.append('action', 'cybreed_fetch_chats');
                formData.append('nonce', settingsNonce.value);
                formData.append('organisation_id', this.value);

                const response = await fetch(ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                });

                const data = await response.json();
                
                if (data.success) {
                    chatSelect.value = ''; // Reset chat selection
                    updateChatSelect(data.chats || []);
                } else {
                    throw new Error(data.message || 'Failed to fetch chats');
                }
            } catch (error) {
                showToast(error.message || 'An error occurred while updating organization', 'error');
                updateChatSelect([]); // Reset chat select on error
            }
        });
    }

    // Handle settings form submission
    if (settingsForm) {
        settingsForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData();
            formData.append('action', 'cybreed_save_all_settings');
            formData.append('nonce', document.querySelector('#cybreed_settings_nonce').value);
            formData.append('organisation_id', orgSelect ? orgSelect.value : '');
            formData.append('chat_id', chatSelect ? chatSelect.value : '');
            formData.append('display_type', document.querySelector('#cybreed_display_type').value);

            // Add specific pages
            const specificPages = document.querySelectorAll('input[name="specific_pages[]"]:checked');
            specificPages.forEach(checkbox => {
                formData.append('specific_pages[]', checkbox.value);
            });

            // Add excluded pages
            const excludedPages = document.querySelectorAll('input[name="excluded_pages[]"]:checked');
            excludedPages.forEach(checkbox => {
                formData.append('excluded_pages[]', checkbox.value);
            });

            // Add single page
            const singlePage = document.querySelector('select[name="cybreed_single_page_id"]');
            if (singlePage) formData.append('cybreed_single_page_id', singlePage.value);

            // Disable save button while processing
            const saveButton = this.querySelector('button[type="submit"]');
            const originalText = saveButton.textContent;
            saveButton.textContent = 'Saving...';
            saveButton.disabled = true;

            fetch(ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Settings saved successfully', 'success');
                    const selectedChatId = chatSelect ? chatSelect.value : '';
                    if (data.chats) {
                        updateChatSelect(data.chats);
                        if (selectedChatId) {
                            chatSelect.value = selectedChatId;
                        }
                    }
                } else {
                    showToast(data.message || 'Failed to save settings', 'error');
                }
            })
            .catch(error => {
                showToast('An error occurred while saving settings', 'error');
            })
            .catch(error => {
                showToast('An error occurred while updating display settings.', 'error');
            })
            .finally(() => {
                saveButton.textContent = originalText;
                saveButton.disabled = false;
            });
        });
    }

    // Handle logout message
    const messages = document.querySelectorAll('.updated, .error');
    if (messages.length > 0) {
        messages.forEach(message => {
            const type = message.classList.contains('updated') ? 'success' : 'error';
            showToast(message.textContent.trim(), type);
            message.remove();
        });
        
        // If there's a logout success message in the URL, remove it after showing the toast
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('logout') === 'success') {
            const newUrl = window.location.href.replace(/[?&]logout=success/, '');
            window.history.replaceState({}, document.title, newUrl);
        }
    }
});