import { useEffect } from "react";
import useChatUIStore from "../stores/Zustant";
import MessageContainer from "./messages/MessageContainer";
import { Sidebar } from "./sidebar/Sidebar";
import BookingPanel from "./booking/BookingPanel";
import { useChatContext } from "../providers/ChatProvider";
import { ChatUIOptions, ChatUIOptionsProvider } from "../providers/ChatUIOptions";

export type ChatProps = ChatUIOptions;

/**
 * Chat page shell: conversation list | message thread | booking detail panel.
 * The sidebar/topbar around it belong to the host shell.
 */
export const Chat = (options: ChatProps) => {
  const { selectedConversation, updateMessageStatus } = useChatUIStore();
  const { socket, sendMessage } = useChatContext();
  const { showBookingPanel = true } = options;

  useEffect(() => {
    if (!socket) return;

    const handleMessage = (event: MessageEvent) => {
      try {
        const parsed = JSON.parse(event.data);

        if (parsed.event === "newMessage") {
          const message = parsed.data.data;
          sendMessage({
            event: "confirmDelivery",
            data: {
              messageIds: [message._id],
              chatId: message.conversationId,
              senderRole: message.senderRole,
              receiverRole: message.receiverRole,
              senderId: message.senderId,
              receiverId: message.receiverId,
            },
          });

          updateMessageStatus(message._id, "delivered");

          // Only mark read if the message belongs to the open conversation
          if (message.conversationId === selectedConversation?._id) {
            sendMessage({
              event: "messageRead",
              data: {
                messageIds: [message._id],
                chatId: message.conversationId,
                senderId: message.senderId,
                receiverId: message.receiverId,
                receiverRole: message.receiverRole,
                senderRole: message.senderRole,
              },
            });
          }
        }
      } catch (error) {
        console.error("WebSocket message parse error:", error);
      }
    };

    socket.addEventListener("message", handleMessage);
    return () => socket.removeEventListener("message", handleMessage);
  }, [socket, sendMessage, updateMessageStatus, selectedConversation]);

  return (
    <ChatUIOptionsProvider value={options}>
      <div className="chat-page__wrapper">
        <div className="chat-page">
          {/* On narrow screens the list and thread swap rather than sit side by side. */}
          <div
            className={`chat-page__list ${
              selectedConversation ? "mobile-hidden" : "mobile-visible"
            }`}
          >
            <Sidebar />
          </div>

          <div
            className={`chat-page__thread ${
              selectedConversation ? "mobile-visible" : "mobile-hidden"
            }`}
          >
            <MessageContainer />
          </div>

          {showBookingPanel && <BookingPanel />}
        </div>
      </div>
    </ChatUIOptionsProvider>
  );
};
