import React, { useState, useEffect, useRef } from 'react';
import { getNonce, getConfig, adminAjax } from './Helpers';
import { initializeApp } from 'firebase/app';
import {
    getAuth,
    signInWithPopup,
    GoogleAuthProvider,
    signInWithEmailAndPassword,
    createUserWithEmailAndPassword,
    onAuthStateChanged,
    signOut,
    updateProfile
} from 'firebase/auth';
import {
    getFirestore,
    collection,
    addDoc,
    query,
    orderBy,
    limit,
    onSnapshot,
    serverTimestamp,
    where,
    doc,
    updateDoc,
    setDoc,
    getDocs,
    deleteDoc
} from 'firebase/firestore';
import {
    getStorage,
    ref,
    uploadBytes,
    getDownloadURL
} from 'firebase/storage';

const ShortcodeWidget = ({ config, containerId }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [isMinimized, setIsMinimized] = useState(false);
    const [user, setUser] = useState(null);
    const [users, setUsers] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    

    const messagesEndRef = useRef(null);
    const fileInputRef = useRef(null);
    const [firebaseConfig, setFirebaseConfig] = useState(null);
    const [app, setApp] = useState(null);
    const [auth, setAuth] = useState(null);
    const [db, setDb] = useState(null);
    const [storage, setStorage] = useState(null);

    // Use shortcode config or fallback to global config
    const widgetConfig = config || {
        position: 'bottom-right',
        title: 'Chat Support',
        description: 'Need help? Chat with our team!',
        color: '#5A5EB9'
    };

    useEffect(() => {
        // Get Firebase config from WordPress
        const fbConfig = getConfig();

        if (fbConfig && fbConfig.apiKey) {
            setFirebaseConfig(fbConfig);
            try {
                const firebaseApp = initializeApp(fbConfig);
                const firebaseAuth = getAuth(firebaseApp);
                const firestoreDb = getFirestore(firebaseApp);
                const firebaseStorage = getStorage(firebaseApp);

                setApp(firebaseApp);
                setAuth(firebaseAuth);
                setDb(firestoreDb);
                setStorage(firebaseStorage);

                // Listen for auth state changes
                const unsubscribe = onAuthStateChanged(firebaseAuth, (user) => {
                    setUser(user);
                    setLoading(false);
                    if (user) {
                        updateUserStatus(user, true);
                        authenticateWithWordPress(user);
                    }
                });

                return () => unsubscribe();
            } catch (error) {
                console.error('Firebase initialization error:', error);
                setFirebaseError('Failed to initialize Firebase: ' + error.message);
                setLoading(false);
            }
        } else {
            setFirebaseError('Firebase configuration not found.');
            setLoading(false);
        }
    }, []);

    // Load support system settings and current user admin status
    useEffect(() => {
        if (user) {
            loadSupportSystemSettings();
            checkCurrentUserAdminStatus();
        }
    }, [user]);

   
    const getChatId = (uid1, uid2) => {
        return [uid1, uid2].sort().join('_');
    };

    const authenticateWithWordPress = async (firebaseUser) => {
        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_firebase_auth',
                    nonce: getNonce(),
                    firebase_uid: firebaseUser.uid,
                    user_name: firebaseUser.displayName || firebaseUser.email,
                    user_email: firebaseUser.email,
                    user_avatar: firebaseUser.photoURL || '',
                    auth_provider: firebaseUser.providerData[0]?.providerId || 'email'
                })
            });

            const data = await response.json();
            if (!data.success) {
                console.error('WordPress authentication failed:', data.data);
            }
        } catch (error) {
            console.error('Error authenticating with WordPress:', error);
        }
    };

    const signInWithGoogle = async () => {
        if (!auth) return;

        const provider = new GoogleAuthProvider();
        provider.setCustomParameters({
            prompt: 'select_account'
        });

        try {
            await signInWithPopup(auth, provider);
        } catch (error) {
            console.error('Google sign-in error:', error);
            setFirebaseError('Google sign-in failed: ' + error.message);
        }
    };

    

    const handleFileUpload = async (file) => {
        if (!storage || !file) return;

        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            setFirebaseError('File too large. Maximum size is 10MB.');
            return;
        }

        setUploading(true);
        try {
            const storageRef = ref(storage, `chat-files/${Date.now()}_${file.name}`);
            const snapshot = await uploadBytes(storageRef, file);
            const downloadURL = await getDownloadURL(snapshot.ref);

            const fileType = file.type.startsWith('image/') ? 'image' : 'file';
            await sendMessage('', fileType, downloadURL, file.name);
        } catch (error) {
            console.error('Error uploading file:', error);
            setFirebaseError('File upload failed: ' + error.message);
        } finally {
            setUploading(false);
        }
    };

    const uploadProfileImage = async (file) => {
        if (!storage || !file) return null;

        try {
            const storageRef = ref(storage, `profile-images/${Date.now()}_${file.name}`);
            const snapshot = await uploadBytes(storageRef, file);
            const downloadURL = await getDownloadURL(snapshot.ref);
            return downloadURL;
        } catch (error) {
            console.error('Error uploading profile image:', error);
            return null;
        }
    };

    const filteredUsers = users.filter(user => {
        let shouldShow = true;

        if (supportSystemEnabled) {
            if (currentUserIsAdmin) {
                shouldShow = true;
            } else {
                shouldShow = user.isAdmin === true;
            }
        }

        if (!shouldShow) return false;

        if (!searchTerm.trim()) return true;

        const searchLower = searchTerm.toLowerCase();
        const displayName = user.displayName?.toLowerCase() || '';
        const email = user.email?.toLowerCase() || '';

        return displayName.includes(searchLower) || email.includes(searchLower);
    });

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = timestamp.toDate ? timestamp.toDate() : new Date(timestamp);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    };

    const loadSupportSystemSettings = 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);
            }
        } catch (error) {
            console.error('Error loading support settings:', error);
        }
    };

    const checkCurrentUserAdminStatus = async () => {
        if (!user) return;

        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_check_user_admin_status',
                    nonce: getNonce(),
                    firebase_uid: user.uid
                })
            });

            const data = await response.json();
            if (data.success) {
                setCurrentUserIsAdmin(data.data.is_admin);
            }
        } catch (error) {
            console.error('Error checking admin status:', error);
            setCurrentUserIsAdmin(false);
        }
    };

    const fetchUsersWithAdminStatus = async (firestoreUsers) => {
        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_users',
                    nonce: getNonce(),
                    current_user_uid: user?.uid || ''
                })
            });

            const data = await response.json();

            if (data.success) {
                const wpUsers = data.data.users;

                const mergedUsers = firestoreUsers.map(firestoreUser => {
                    const wpUser = wpUsers.find(wp => wp.firebase_uid === firestoreUser.uid);
                    const isAdmin = wpUser ? Boolean(wpUser.is_admin) : false;

                    return {
                        ...firestoreUser,
                        isAdmin: isAdmin,
                        wpUserId: wpUser ? wpUser.id : null
                    };
                });

                return mergedUsers;
            } else {
                return firestoreUsers.map(user => ({ ...user, isAdmin: false }));
            }
        } catch (error) {
            console.error('Error fetching users with admin status:', error);
            return firestoreUsers.map(user => ({ ...user, isAdmin: false }));
        }
    };

    if (loading) {
        return null;
    }

    if (firebaseError) {
        return null;
    }

    // Get position styles for shortcode
    const getPositionStyles = () => {
        const position = widgetConfig.position;
        const styles = {
            '--acb-primary-color': widgetConfig.color
        };

        switch (position) {
            case 'bottom-right':
                return { ...styles, position: 'fixed', bottom: '20px', right: '20px', zIndex: 9999 };
            case 'bottom-left':
                return { ...styles, position: 'fixed', bottom: '20px', left: '20px', zIndex: 9999 };
            case 'top-right':
                return { ...styles, position: 'fixed', top: '20px', right: '20px', zIndex: 9999 };
            case 'top-left':
                return { ...styles, position: 'fixed', top: '20px', left: '20px', zIndex: 9999 };
            case 'inline':
                return { ...styles, position: 'relative', display: 'block', margin: '20px 0' };
            default:
                return { ...styles, position: 'fixed', bottom: '20px', right: '20px', zIndex: 9999 };
        }
    };

    return (
        <div className={`acb-widget-container acb-shortcode-widget acb-position-${widgetConfig.position}`} style={getPositionStyles()}>
            {/* Call-to-Action Description */}
            {!isOpen && widgetConfig.description && widgetConfig.description.trim() && (
                <div className="acb-widget-cta" style={{ '--acb-primary-color': widgetConfig.color }}>
                    <div className="acb-widget-cta-content">
                        <span className="acb-widget-cta-text">{widgetConfig.description}</span>
                        <div className="acb-widget-cta-wave">👋</div>
                    </div>
                </div>
            )}
            
            {/* Floating Chat Button */}
            <div
                className={`acb-widget-button ${isOpen ? 'hidden' : ''}`}
                onClick={() => setIsOpen(true)}
                style={{ backgroundColor: widgetConfig.color }}
            >
                <i className="fas fa-comments"></i>
                {unreadCount > 0 && (
                    <span className="acb-widget-badge">{unreadCount}</span>
                )}
            </div>

            {/* Chat Widget */}
            {isOpen && (
                <div className={`acb-widget ${isMinimized ? 'minimized' : ''}`}>
                    {/* Widget Header */}
                    <div className="acb-widget-header" style={{ backgroundColor: widgetConfig.color }}>
                        <div className="acb-widget-title">
                            <i className="fas fa-comments"></i>
                            <span>{widgetConfig.title}</span>
                        </div>
                        <div className="acb-widget-controls">
                            <button
                                className="acb-widget-minimize"
                                onClick={() => setIsMinimized(!isMinimized)}
                            >
                                <i className={`fas fa-${isMinimized ? 'expand' : 'minus'}`}></i>
                            </button>
                            <button
                                className="acb-widget-close"
                                onClick={() => setIsOpen(false)}
                            >
                                <i className="fas fa-times"></i>
                            </button>
                        </div>
                    </div>

                    {!isMinimized && (
                        <div className="acb-widget-content">
                            {!user ? (
                                // Login/Register Form
                                <div className="acb-widget-auth">
                                    <h3>{widgetConfig.title}</h3>
                                    <p>{widgetConfig.description}</p>

                                    <button
                                        className="acb-widget-google-btn"
                                        onClick={signInWithGoogle}
                                    >
                                        <i className="fab fa-google"></i>
                                        Sign in with Google
                                    </button>

                                    <div className="acb-widget-divider">
                                        <span>or</span>
                                    </div>

                                    <button
                                        className="acb-widget-email-btn"
                                        onClick={() => setShowLogin(true)}
                                    >
                                        Sign in with Email
                                    </button>

                                    {showLogin && (
                                        <div className="acb-widget-email-form">
                                            {isSignUp && (
                                                <input
                                                    type="text"
                                                    placeholder="Display Name"
                                                    value={signUpDisplayName}
                                                    onChange={(e) => setSignUpDisplayName(e.target.value)}
                                                />
                                            )}
                                            <input
                                                type="email"
                                                placeholder="Email"
                                                value={loginEmail}
                                                onChange={(e) => setLoginEmail(e.target.value)}
                                            />
                                            <input
                                                type="password"
                                                placeholder="Password"
                                                value={loginPassword}
                                                onChange={(e) => setLoginPassword(e.target.value)}
                                            />
                                            <button onClick={signInWithEmail}>
                                                {isSignUp ? 'Sign Up' : 'Sign In'}
                                            </button>
                                            <button
                                                className="acb-widget-toggle-signup"
                                                onClick={() => setIsSignUp(!isSignUp)}
                                            >
                                                {isSignUp ? 'Already have an account? Sign In' : 'Need an account? Sign Up'}
                                            </button>
                                        </div>
                                    )}

                                    {firebaseError && (
                                        <div className="acb-widget-error">
                                            {firebaseError}
                                        </div>
                                    )}
                                </div>
                            ) : (
                                // Chat Interface
                                <div className="acb-widget-chat">
                                    <div className="acb-widget-users">
                                        <div className="acb-widget-user-header">
                                            <div className="acb-widget-current-user">
                                                <img src={user.photoURL || 'https://via.placeholder.com/32'} alt="User" className="acb-widget-user-avatar" />
                                                <span>{user.displayName || user.email}</span>
                                            </div>
                                            <button onClick={handleSignOut} className="acb-widget-signout">
                                                <i className="fas fa-sign-out-alt"></i>
                                            </button>
                                        </div>

                                        <input
                                            className="acb-widget-search"
                                            type="text"
                                            placeholder="Search users..."
                                            value={searchTerm}
                                            onChange={(e) => setSearchTerm(e.target.value)}
                                        />

                                        <div className="acb-widget-users-list">
                                            {filteredUsers.map(chatUser => (
                                                <div
                                                    key={chatUser.uid}
                                                    className={`acb-widget-user-item ${selectedUser?.uid === chatUser.uid ? 'active' : ''}`}
                                                    onClick={() => setSelectedUser(chatUser)}
                                                >
                                                    <img src={chatUser.photoURL || 'https://via.placeholder.com/32'} alt="User" className="acb-widget-user-avatar" />
                                                    <div className="acb-widget-user-info">
                                                        <div className="acb-widget-user-name">
                                                            {chatUser.displayName || chatUser.email}
                                                            {chatUser.isAdmin && <span className="acb-admin-badge"> Admin</span>}
                                                        </div>
                                                        <div className={`acb-widget-user-status ${chatUser.isOnline ? 'online' : 'offline'}`}>
                                                            {chatUser.isOnline ? 'Online' : 'Offline'}
                                                        </div>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    <div className="acb-widget-chat-area">
                                        {selectedUser ? (
                                            <>
                                                <div className="acb-widget-chat-header">
                                                    <img src={selectedUser.photoURL || 'https://via.placeholder.com/32'} alt="User" className="acb-widget-user-avatar" />
                                                    <span>{selectedUser.displayName || selectedUser.email}</span>
                                                </div>

                                                <div className="acb-widget-messages">
                                                    {messages.map(message => (
                                                        <div
                                                            key={message.id}
                                                            className={`acb-widget-message ${message.uid === user.uid ? 'own' : 'other'}`}
                                                        >
                                                            <div className="acb-widget-message-content">
                                                                {message.type === 'image' ? (
                                                                    <img src={message.fileUrl} alt="Shared image" className="acb-widget-message-image" />
                                                                ) : message.type === 'file' ? (
                                                                    <div className="acb-widget-message-file">
                                                                        <i className="fas fa-file"></i>
                                                                        <a href={message.fileUrl} target="_blank" rel="noopener noreferrer">
                                                                            {message.fileName}
                                                                        </a>
                                                                    </div>
                                                                ) : (
                                                                    <p>{message.text}</p>
                                                                )}
                                                                <div className="acb-widget-message-time">
                                                                    {formatTime(message.timestamp)}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    ))}
                                                    <div ref={messagesEndRef} />
                                                </div>

                                                <div className="acb-widget-input">
                                                    <button
                                                        className="acb-widget-attach"
                                                        onClick={() => fileInputRef.current?.click()}
                                                        disabled={uploading}
                                                    >
                                                        <i className="fas fa-paperclip"></i>
                                                    </button>
                                                    <input
                                                        type="text"
                                                        placeholder="Type a message..."
                                                        value={newMessage}
                                                        onChange={(e) => setNewMessage(e.target.value)}
                                                        onKeyPress={(e) => e.key === 'Enter' && sendMessage(newMessage)}
                                                        disabled={uploading}
                                                    />
                                                    <button
                                                        onClick={() => sendMessage(newMessage)}
                                                        disabled={!newMessage.trim() && !uploading}
                                                    >
                                                        {uploading ? (
                                                            <i className="fas fa-spinner fa-spin"></i>
                                                        ) : (
                                                            <i className="fas fa-paper-plane"></i>
                                                        )}
                                                    </button>

                                                    <input
                                                        ref={fileInputRef}
                                                        type="file"
                                                        onChange={(e) => {
                                                            const file = e.target.files[0];
                                                            if (file) {
                                                                handleFileUpload(file);
                                                            }
                                                            e.target.value = '';
                                                        }}
                                                        style={{ display: 'none' }}
                                                        accept="image/*,.pdf,.doc,.docx,.txt"
                                                    />
                                                </div>
                                            </>
                                        ) : (
                                            <div className="acb-widget-no-chat">
                                                <i className="fas fa-comments"></i>
                                                <p>Select a user to start chatting</p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default ShortcodeWidget;