import { useEffect, useState } from "preact/hooks";

interface ChatMessage {
  text: string;
  sender: string;
  timestamp: string;
}

export default function Chat() {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState("");
  const [username, setUsername] = useState("");
  const [socket, setSocket] = useState<WebSocket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [userCount, setUserCount] = useState(0);

  useEffect(() => {
    if (!username) {
      const randomNum = Math.floor(Math.random() * 10000);
      setUsername(`HumanGuest${randomNum}`);
    }

    const wsProtocol = globalThis.location.protocol === "https:"
      ? "wss:"
      : "ws:";
    const ws = new WebSocket(
      `${wsProtocol}//${globalThis.location.host}/api/chat`,
    );

    ws.onopen = () => {
      console.log("Connected to chat");
      setIsConnected(true);
      setSocket(ws);
    };

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === "user_count") {
          setUserCount(data.count);
        } else {
          setMessages((prev) => [...prev, data]);

          // Auto-scroll to bottom on new message
          const chatBox = document.getElementById("chat-messages");
          if (chatBox) {
            setTimeout(() => {
              chatBox.scrollTop = chatBox.scrollHeight;
            }, 50);
          }
        }
      } catch (err) {
        console.error("Error processing message:", err);
      }
    };

    ws.onclose = () => {
      console.log("Disconnected from chat");
      setIsConnected(false);
    };

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

  const sendMessage = (e: Event) => {
    e.preventDefault();
    if (!newMessage.trim() || !socket) return;

    const messageData = {
      text: newMessage,
      sender: username,
      timestamp: new Date().toISOString(),
    };

    socket.send(JSON.stringify(messageData));
    setNewMessage("");
  };

  return (
    <div class="w-full max-w-4xl mx-auto bg-[#1E2127] rounded-lg shadow-lg overflow-hidden border border-gray-800 flex flex-col h-[70vh]">
      {/* Header */}
      <div class="p-4 bg-secondary text-white">
        <h2 class="text-2xl font-bold">Live Chat</h2>
        <p class="text-sm">
          {isConnected
            ? `${userCount} online • Messages are not saved`
            : "Connecting..."}
        </p>
      </div>

      <div
        id="chat-messages"
        class="flex-grow overflow-y-auto bg-[#1E2127] text-gray-300 p-4"
      >
        {messages.length === 0
          ? (
            <p class="text-center text-gray-500 py-8">
              No messages yet.
            </p>
          )
          : (
            messages.map((msg, i) => (
              <div
                key={i}
                class={`mb-3 max-w-[85%] ${
                  msg.sender === username ? "ml-auto" : ""
                }`}
              >
                <div
                  class={`px-4 py-2 rounded-lg ${
                    msg.sender === username
                      ? "bg-secondary text-white rounded-br-none"
                      : "bg-gray-800 text-gray-200 rounded-bl-none"
                  }`}
                >
                  <div class="flex justify-between items-baseline mb-1">
                    <span class="font-bold text-sm">
                      {msg.sender === username ? "You" : msg.sender}
                    </span>
                    <span class="text-xs opacity-70 ml-2">
                      {new Date(msg.timestamp).toLocaleTimeString([], {
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </span>
                  </div>
                  <p class="break-words">{msg.text}</p>
                </div>
              </div>
            ))
          )}
      </div>

      <div class="p-3 border-t border-gray-800 pb-6 md:pb-3">
        <form onSubmit={sendMessage} class="relative">
          <input
            type="text"
            value={newMessage}
            onChange={(e) => setNewMessage(e.currentTarget.value)}
            placeholder="Type your message..."
            class="w-full pl-4 pr-20 py-3 bg-gray-800 text-white rounded-lg border-0 focus:outline-none focus:ring-1 focus:ring-secondary placeholder-gray-500"
            disabled={!isConnected}
          />
          <button
            type="submit"
            class="absolute right-0 top-0 h-full bg-secondary text-white px-5 rounded-r-lg font-medium"
            disabled={!isConnected || !newMessage.trim()}
          >
            Send
          </button>
        </form>
        <p class="mt-2 text-xs text-gray-500">
          You are connected as{" "}
          <span class="font-medium text-gray-400">{username}</span>
        </p>
      </div>
    </div>
  );
}
