import React, { useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import "./css/Chat.css";
import { FaPaperPlane, FaSmile } from "react-icons/fa";

const emojis = [
  "😀",
  "😁",
  "😂",
  "🤣",
  "😃",
  "😄",
  "😅",
  "😆",
  "😉",
  "😊",
  "😋",
  "😎",
  "😍",
  "😘",
  "🥰",
  "😗",
  "😙",
  "😚",
  "🙂",
  "🤗",
  "🤩",
  "🤔",
  "😐",
  "😑",
  "😶",
  "🙄",
  "😏",
  "😣",
  "😥",
  "😮",
  "🤐",
  "😯",
  "😪",
  "😫",
  "😴",
  "😌",
  "😛",
  "😜",
  "🤪",
  "🤨",
  "😝",
  "🤑",
  "😒",
  "😓",
  "😔",
  "😕",
  "😖",
  "😞",
  "😟",
  "😠",
  "😡",
  "🤬",
  "😱",
  "😨",
  "😧",
  "😇",
  "🥳",
  "🥺",
  "😻",
  "😼",
  "😽",
  "🙈",
  "🙉",
  "🙊",
  "💀",
  "👻",
  "👽",
];

const Chat = () => {
  const [interlocutorId, setInterlocutorId] = useState(0);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState("");
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const socket = useRef(null);
  const chatRef = useRef(null);
  const navigate = useNavigate();

  useEffect(() => {
    const id = parseInt(localStorage.getItem("interlocutorId"), 10) || 0;
    setInterlocutorId(id);

    socket.current = new WebSocket("ws://localhost:8080");

    socket.current.onopen = () => {
      console.log("WebSocket connected");
      socket.current.send(
        JSON.stringify({ type: "register", userId: "yourUserId" })
      );
    };

    socket.current.onmessage = (event) => {
      const receivedData = JSON.parse(event.data);
      setMessages((prev) => [...prev, receivedData]);
    };

    socket.current.onerror = (event) => {
      console.error("WebSocket error observed:", event);
    };

    socket.current.onclose = () => {
      console.log("WebSocket closed");
    };

    return () => {
      socket.current.close();
    };
  }, []);

  useEffect(() => {
    if (chatRef.current) {
      chatRef.current.scrollTop = chatRef.current.scrollHeight;
    }
  }, [messages]);

  const sendMessage = () => {
    if (newMessage.trim()) {
      const messageData = {
        type: "message",
        senderId: "yourUserId",
        recipientId: interlocutorId,
        message: newMessage,
        timestamp: new Date().toLocaleTimeString(),
      };
      socket.current.send(JSON.stringify(messageData));
      setMessages((prev) => [...prev, messageData]);
      setNewMessage("");
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      sendMessage();
    }
  };

  const handleEmojiSelect = (emoji) => {
    setNewMessage((prev) => prev + emoji);
    setShowEmojiPicker(false);
  };

  return (
    <div className="chat-container">
      <div className="chat-header">
        <h2>Chat with ... (id = {interlocutorId})</h2>
        <button
          onClick={() => navigate("/enterfront/home")}
          className="home-button"
        >
          Home
        </button>{" "}
        {}
      </div>
      <div className="chat-messages" ref={chatRef}>
        {messages.map((msg, index) => (
          <div
            key={index}
            className={`message-bubble ${
              msg.senderId === "yourUserId" ? "sent" : "received"
            }`}
          >
            <div className="message-content">
              <b>{msg.senderId === "yourUserId" ? "You" : "Interlocutor"}:</b>{" "}
              {msg.message}
            </div>
            <span className="message-timestamp">{msg.timestamp}</span>
          </div>
        ))}
      </div>
      <div className="chat-input-container">
        <input
          type="text"
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          placeholder="Type a message..."
          className="chat-input"
          onKeyPress={handleKeyPress}
        />
        <button
          className="emoji-button"
          onClick={() => setShowEmojiPicker((prev) => !prev)}
        >
          <FaSmile />
        </button>
        <button onClick={sendMessage} className="send-button">
          <FaPaperPlane />
        </button>
        {showEmojiPicker && (
          <div className="emoji-picker">
            {emojis.map((emoji, index) => (
              <span
                key={index}
                className="emoji"
                onClick={() => handleEmojiSelect(emoji)}
                style={{ cursor: "pointer", padding: "5px" }}
              >
                {emoji}
              </span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Chat;
