import React, { useState, useEffect } from "react";
import io from "socket.io-client";

// Inisialisasi koneksi ke server
const socket = io("http://localhost:3001"); // Pastikan mengganti dengan URL server Socket.IO Anda

const CustomerChat = () => {
    const [message, setMessage] = useState("");
    const [messages, setMessages] = useState([]);

    // Efek untuk mendengarkan pesan baru dari server
    useEffect(() => {
        socket.on("receiveMessage", (newMessage) => {
            setMessages((prevMessages) => [...prevMessages, newMessage]);
        });

        // Cleanup connection on component unmount
        return () => {
            socket.off("receiveMessage");
        };
    }, []);

    // Fungsi untuk mengirim pesan
    const sendMessage = () => {
        if (message.trim() !== "") {
            socket.emit("sendMessage", { sender: "customer", text: message }); // Kirim pesan ke server
            setMessages((prevMessages) => [...prevMessages, { sender: "customer", text: message }]); // Tampilkan pesan di client
            setMessage(""); // Bersihkan input setelah kirim pesan
        }
    };

    return (
        <div style={{ padding: "20px", maxWidth: "400px", margin: "auto" }}>
            <h2>Customer Service Chat</h2>
            <div
                style={{
                    border: "1px solid #ccc",
                    height: "300px",
                    overflowY: "scroll",
                    marginBottom: "10px",
                    padding: "10px",
                    backgroundColor: "#f9f9f9"
                }}
            >
                {messages.map((msg, index) => (
                    <div
                        key={index}
                        style={{
                            textAlign: msg.sender === "customer" ? "right" : "left",
                            backgroundColor: msg.sender === "customer" ? "#d1e7dd" : "#fff3cd",
                            padding: "10px",
                            borderRadius: "10px",
                            marginBottom: "5px",
                            maxWidth: "70%",
                            marginLeft: msg.sender === "customer" ? "auto" : "0",
                        }}
                    >
                        {msg.text}
                    </div>
                ))}
            </div>
            <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                style={{ width: "80%", padding: "10px", marginRight: "10px", borderRadius: "5px" }}
                placeholder="Ketik pesan..."
            />
            <button
                onClick={sendMessage}
                style={{ padding: "10px 20px", backgroundColor: "#007bff", color: "#fff", border: "none", borderRadius: "5px" }}
            >
                Kirim
            </button>
        </div>
    );
};

export default CustomerChat;
