import { user } from "@localtypes";
import { sendChatMessage, token, self, getUsers, subscribeUsers } from "@ws";
import { useRef, useState, useSyncExternalStore, type ReactElement } from "react";

export function Chatbar(): ReactElement {
  const [message, setMessage] = useState("");
  const users: user[] = useSyncExternalStore(
    subscribeUsers,
    getUsers
  );

  const editorRef = useRef<HTMLDivElement | null>(null);

  function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      if (message.trim() !== "") {
        const msg = replaceMentions(message.trim());
        sendChatMessage({id: Date.now(), author: self, content: msg, timestamp: Date.now(), token: token!, hasSent: false});
        console.log("Sent message:", msg);
        setMessage("");
        if (editorRef.current) {
          editorRef.current.innerText = "";
        }
      }
    }
  };
  function replaceMentions(
    text: string,
  ): string {
    // Build a quick lookup map: username -> id
    const userMap = new Map(
      users.map(u => [u.username, u.id])
    );

    console.log(userMap);

    // Match @[username] (username = anything except ])
    return text.replace(/@(\S+)/g, (match, username) => {
      const userId = userMap.get(username);
      console.log(userId);
      return userId ? `<@${userId}>` : match;
    });
  }

  function handleChange(event: React.FormEvent<HTMLDivElement>) {
    if (editorRef.current) {
      setMessage(editorRef.current.innerText.trim());
      if (editorRef.current.innerText === "\n") {
        editorRef.current.innerHTML = "";
      }
    }
  };

  return (
    <div className="textbox">
      <div
        ref={editorRef}
        className="editor"
        contentEditable
        onKeyDown={handleKeyDown}
        onInput={handleChange}
        data-text="Type here..."
      ></div>
    </div>
  );
}