import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import './DashboardChat.css';

const socket = io('http://localhost:3001');

const DashboardChat = () => {
    const [message, setMessage] = useState('');
    const [messages, setMessages] = useState([]);
    const [users, setUsers] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    const [profileMenuVisible, setProfileMenuVisible] = useState(false);
    const [adminProfile, setAdminProfile] = useState({
        name: 'Admin',
        avatar: 'https://i.pravatar.cc/150?u=admin'
    });
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    useEffect(() => {
        socket.on('receiveMessage', (message) => {
            console.log('Received message in DashboardChat:', message);
            setMessages(prevMessages => [...prevMessages, message]);
        });

        socket.on('updateUsers', (updatedUsers) => {
            console.log('Updated users:', updatedUsers);
            setUsers(updatedUsers);
        });

        fetch('http://localhost:3001/users')
            .then(response => response.json())
            .then(data => {
                setUsers(Object.values(data));
                setLoading(false);
            })
            .catch(error => {
                console.error('Error fetching users:', error);
                setError('Failed to fetch users. Please try again later.');
                setLoading(false);
            });

        return () => {
            socket.off('receiveMessage');
            socket.off('updateUsers');
        };
    }, []);

    const sendMessage = () => {
        if (message.trim() && selectedUser) {
            const messageData = { content: message, sender: 'admin', recipient: selectedUser.id };
            console.log('Sending message:', messageData);
            socket.emit('sendMessage', messageData);
            setMessage('');
        }
    };

    const handleLogout = () => {
        fetch('http://localhost:3001/logoutAdmin', {
            method: 'POST',
            credentials: 'include'
        }).then(() => {
            window.location.href = '/loginAdmin';
        }).catch(error => console.error('Logout failed:', error));
    };

    const endConversation = () => {
        if (selectedUser) {
            socket.emit('endConversation', { recipient: selectedUser.id });
            setMessages(prevMessages => prevMessages.filter(msg => msg.recipient !== selectedUser.id));
            setSelectedUser(null);
        }
    };

    const deleteUser = (userId) => {
        console.log(`Attempting to delete user with ID ${userId}`);
        fetch('http://localhost:3001/deleteUser', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: userId }),
            credentials: 'include'
        }).then(() => {
            console.log(`User with ID ${userId} deleted successfully`);
            setUsers(prevUsers => prevUsers.filter(user => user.id !== userId));
            setSelectedUser(null);
        }).catch(error => console.error('Failed to delete user:', error));
    };

    const deleteMessages = () => {
        if (selectedUser) {
            fetch('http://localhost:3001/deleteMessages', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ recipient: selectedUser.id }),
                credentials: 'include'
            }).then(() => {
                setMessages(prevMessages => prevMessages.filter(msg => msg.recipient !== selectedUser.id && msg.sender !== selectedUser.id));
            }).catch(error => console.error('Failed to delete messages:', error));
        }
    };

    const toggleProfileMenu = () => {
        setProfileMenuVisible(prevState => !prevState);
    };

    return (
        <div className="dashboard-chat">
            <div className="sidebar">
                <h2>Users</h2>
                {loading ? (
                    <div className="loading">Loading...</div>
                ) : error ? (
                    <div className="error">{error}</div>
                ) : (
                    <ul>
                        {users.map(user => (
                            <li
                                key={user.id}
                                onClick={() => setSelectedUser(user)}
                                className={selectedUser?.id === user.id ? 'active' : ''}
                            >
                                {user.name}
                            </li>
                        ))}
                    </ul>
                )}
            </div>
            <div className="chat">
                <div className="header">
                    <span>Chat with {selectedUser?.name || 'Select a user'}</span>
                    <div className="admin-profile">
                        <img
                            src={adminProfile.avatar}
                            alt="Admin"
                            onClick={toggleProfileMenu}
                        />
                        {profileMenuVisible && (
                            <div className="profile-menu">
                                <button onClick={handleLogout}>Logout</button>
                            </div>
                        )}
                    </div>
                </div>
                <div className="messages">
                    {messages.filter(msg => msg.recipient === selectedUser?.id || msg.sender === selectedUser?.id)
                        .map((msg, index) => (
                            <div
                                key={index}
                                className={`message ${msg.sender === 'admin' ? 'sent' : 'received'}`}
                            >
                                <strong>{msg.sender}:</strong> {msg.content}
                            </div>
                        ))}
                </div>
                <div className="input-area">
                    <input
                        type="text"
                        value={message}
                        onChange={(e) => setMessage(e.target.value)}
                        placeholder="Type your message here..."
                    />
                    <button onClick={sendMessage}>Send</button>
                </div>
                {selectedUser && (
                    <>
                        <button className="end-conversation" onClick={endConversation}>End Chat</button>
                        <button className="delete-messages" onClick={deleteMessages}>Delete Messages</button>
                    </>
                )}
            </div>
        </div>
    );
};

export default DashboardChat;
