/* eslint-disable @typescript-eslint/no-explicit-any */
import { ChevronLeft, MessageCircle } from "lucide-react";
import { useEffect } from "react";
import MessageInput from "./MessageInput";
import Messages from "./Messages";
import useChatUIStore from "../../stores/Zustant";
import { useChatContext } from "../../providers/ChatProvider";
import { getChatConfig } from "../../Chat.config";
import defaultProfilePicture from "../../assets/pngegg.png";
import Avatar from "../common/Avatar";

const MessageContainer = () => {
  const { userId } = useChatContext();
  const { selectedConversation, setSelectedConversation, setOnlineUsers } =
    useChatUIStore();
  const { socket, isUserOnline } = useChatContext();
  const { role } = getChatConfig();

  useEffect(() => {
    if (!socket || !selectedConversation?._id) return;

    const sendJoinChat = () => {
      socket.send(
        JSON.stringify({
          event: "joinChat",
          data: {
            chatId: selectedConversation._id,
            userId: userId,
            role: role,
          },
        })
      );

      // Bulk-mark all existing unread messages as read when the conversation is opened
      const unreadIds = selectedConversation.unreadMessageIds ?? [];
      const lastMsg = selectedConversation.lastMessage;
      if (unreadIds.length > 0 && lastMsg) {
        socket.send(
          JSON.stringify({
            event: "messageRead",
            data: {
              messageIds: unreadIds,
              chatId: selectedConversation._id,
              senderId: lastMsg.senderId,
              receiverId: userId,
              // roles are not always available here — backend should infer from chatId if needed
            },
          })
        );
      }
    };

    if (socket.readyState === WebSocket.OPEN) {
      // Socket already open — fire immediately
      sendJoinChat();
    } else if (socket.readyState === WebSocket.CONNECTING) {
      // Socket still connecting — wait for it to open, then fire once
      socket.addEventListener("open", sendJoinChat, { once: true });
      return () => socket.removeEventListener("open", sendJoinChat);
    }
  }, [selectedConversation?._id, socket, userId, role]);

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

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

        if (data.event === "getOnlineUsers") {
          setOnlineUsers(data.payload); // payload should be an array of user IDs
        }
      } catch (err) {
        console.error("Failed to parse WebSocket message", err);
      }
    };

    socket.addEventListener("message", handleMessage);

    return () => {
      socket.removeEventListener("message", handleMessage);
    };
  }, [socket, setOnlineUsers]);

  // Listen for online users updates

  const participantDetails = Array.isArray(
    selectedConversation?.participantDetails
  )
    ? selectedConversation?.participantDetails
    : [selectedConversation?.participantDetails].filter(Boolean);

  const participant = participantDetails.find((p: any) => p._id !== userId);

  // const participant = selectedConversation?.participantDetails?.find(
  //   (p: any) => p._id !== userId
  // );

  const isOnline = isUserOnline(participant?._id || "");

  // Cleanup on unmount
  useEffect(() => {
    return () => setSelectedConversation(null);
  }, [setSelectedConversation]);

  if (!selectedConversation) return <EmptyInbox />;

  const isService = selectedConversation.type === "service";

  return (
    <div className="chat-thread">
      <header className="chat-thread__header">
        <button
          type="button"
          className="chat-thread__back"
          aria-label="Back to conversations"
          onClick={() => setSelectedConversation(null)}
        >
          <ChevronLeft size={18} />
        </button>

        {isService ? (
          <span className="chat-thread__service-icon" aria-hidden="true">
            <MessageCircle size={17} />
          </span>
        ) : (
          <Avatar
            name={participant?.name}
            src={participant?.profilePicture || defaultProfilePicture}
            seed={selectedConversation._id}
            size={34}
            isOnline={isOnline}
          />
        )}

        <div className="chat-thread__identity">
          <span className="chat-thread__name">
            {isService
              ? selectedConversation.serviceTitle
              : participant?.name || "Conversation"}
          </span>
          <span className="chat-thread__subtitle">
            {isOnline ? "Online" : "Offline"}
          </span>
        </div>

        {isService && selectedConversation.bookingId && (
          <span className="chat-thread__booking-id">
            #{selectedConversation.bookingId}
          </span>
        )}
      </header>

      <Messages />
      {role !== "admin" && <MessageInput />}
    </div>
  );
};

export default MessageContainer;

// EmptyInbox component remains the same
interface EmptyInboxProps {
  title?: string;
  description?: string;
}

const EmptyInbox: React.FC<EmptyInboxProps> = ({
  title = "No conversation selected",
  description = "Pick a conversation from the list to see the thread here.",
}) => (
  <div className="chat-empty chat-empty--thread">
    <div className="chat-empty__icon" aria-hidden="true">
      <svg
        width="40"
        height="40"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
      </svg>
    </div>
    <p className="chat-empty__title">{title}</p>
    <p className="chat-empty__text">{description}</p>
  </div>
);
