import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import './CustomerChat.css'; // Import CSS for styling

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

const CustomerChat = () => {
    const [name, setName] = useState('');
    const [message, setMessage] = useState('');
    const [messages, setMessages] = useState([]);
    const [dropdownVisible, setDropdownVisible] = useState(false);

    useEffect(() => {
        socket.on('receiveMessage', (message) => {
            setMessages((prevMessages) => [...prevMessages, message]);
        });

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

    const sendMessage = () => {
        if (message.trim() && name.trim()) {
            socket.emit('sendMessage', { content: message, sender: name });
            setMessage('');
        }
    };

    const toggleDropdown = () => {
        setDropdownVisible(!dropdownVisible);
    };

    const handleEndChat = () => {
        socket.emit('endConversation', { recipient: name });
        setMessages([]);
        setDropdownVisible(false);
    };

    return (
        <div className="customer-chat">
            <h1>Customer Chat</h1>
            <div className="chat-container">
                <div className="options-menu" onClick={toggleDropdown}>
                    <span className="dot"></span>
                    <span className="dot"></span>
                    <span className="dot"></span>
                </div>
                {dropdownVisible && (
                    <div className="dropdown-menu show">
                        <button onClick={handleEndChat}>End Chat</button>
                    </div>
                )}
                <div className="message-list">
                    {messages.map((msg, index) => (
                        <div
                            key={index}
                            className={`message-item ${msg.sender === name ? 'self' : 'other'}`}
                        >
                            <strong>{msg.sender}:</strong> {msg.content}
                        </div>
                    ))}
                </div>
                <div className="input-container">
                    <input
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        placeholder="Enter your name..."
                    />
                    <input
                        type="text"
                        value={message}
                        onChange={(e) => setMessage(e.target.value)}
                        placeholder="Type your message..."
                    />
                    <button onClick={sendMessage}>Send</button>
                </div>
            </div>
        </div>
    );
};  

export default CustomerChat;
