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

const Conversation = ({ conversation }: ConversationProps) => {
  const { setSelectedConversation, setOnlineUsers } = useChatUIStore();
  const { socket, isUserOnline } = useChatContext();
  const selectedConversation = useChatUIStore(
    (state) => state.selectedConversation
  );
  const { userId } = useChatContext();
  const { role } = getChatConfig();

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

  const handleSelectConversation = () => {
    // console.log(
    //   "Selected Conversation Data:",
    //   JSON.stringify(conversation, null, 2)
    // );
    setSelectedConversation(conversation as any)
    const unreadMessageIds = conversation.unreadMessageIds || [];
    if (unreadMessageIds.length > 0 && socket?.readyState === WebSocket.OPEN) {
      // console.log("unread messages", unreadMessageIds);

      const message = {
        event: "messageRead",
        data: {
          messageIds: unreadMessageIds,
          senderId: participant?._id,
          receiverId: userId,
          receiverRole: role,
          senderRole: role === "customer" ? "provider" : "customer",
          chatId: conversation._id,
        },
      };
      socket.send(JSON.stringify(message));
    }
  };

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

    const handleMessage = (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data);
        if (data.event === "getOnlineUsers") {
          setOnlineUsers(data.payload);
        }
      } catch (error) {
        console.error("Failed to parse WebSocket message:", error);
      }
    };

    socket.addEventListener("message", handleMessage);

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

  // useEffect(() => {
  //   // console.log("Current conversation state:", conversation);
  // }, [conversation]);

  const isOnline = isUserOnline(participant?._id || "");
  const isSelected = selectedConversation?._id === conversation._id;
  const unreadCount = conversation.unreadMessageCount || 0;
  const conversationName =
    conversation.type === "service" && conversation.bookingId
      ? `Booking #${conversation.bookingId}`
      : participant?.name || "Conversation";

  const formatLastMessageTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();

    const isToday = date.toDateString() === now.toDateString();

    const yesterday = new Date();
    yesterday.setDate(now.getDate() - 1);

    const isYesterday = date.toDateString() === yesterday.toDateString();

    if (isToday) {
      return date.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
    }

    if (isYesterday) {
      return "Yesterday";
    }

    // MM/DD format
    return date.toLocaleDateString("en-US", {
      month: "2-digit",
      day: "2-digit",
    });
  };

  const lastMessageTimestamp = formatLastMessageTime(
    conversation.lastMessage?.updatedAt ||
      conversation.lastMessage?.createdAt ||
      conversation.createdAt
  );

  const preview =
    conversation.lastMessage?.status === "deleted"
      ? "This message was deleted"
      : conversation.lastMessage?.media?.length > 0
      ? "📎 Attachment"
      : conversation.lastMessage?.message || "";

  return (
    <div
      className={`conversation-row${isSelected ? " conversation-row--selected" : ""}`}
      onClick={handleSelectConversation}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          handleSelectConversation();
        }
      }}
    >
      {conversation.type === "service" ? (
        <span className="conversation-row__service-icon" aria-hidden="true">
          <MessageCircle size={16} />
        </span>
      ) : (
        <Avatar
          name={participant?.name}
          src={participant?.profilePicture || defaultProfilePicture}
          seed={conversation._id}
          size={34}
          isOnline={isOnline}
        />
      )}

      <div className="conversation-row__body">
        <div className="conversation-row__line">
          <span className="conversation-row__name">{conversationName}</span>
          <span className="conversation-row__time">{lastMessageTimestamp}</span>
        </div>
        <div className="conversation-row__line">
          <span className="conversation-row__preview">{preview}</span>
          {unreadCount > 0 && (
            <span className="conversation-row__badge">{unreadCount}</span>
          )}
        </div>
      </div>
    </div>
  );
};

export default memo(Conversation);