import React, { useEffect, useState, useRef } from "react";
import { useAppSelector } from "../hooks/hooks";
import useApiPost from "../hooks/postData";
import formatTimeSimple from "../components/formatUTCTime";
import { BsChevronDown } from "react-icons/bs";
import OpenImage from "./OpenImageComponent";
import { profile } from "console";
import { clearNewUser } from "../store/Slice/NewUserChatSlice";
import { useAppDispatch } from "../hooks/hooks";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import { setSelectedUser, updateSelectedUser, addToChatList, updateChatListOrder } from "../store/Slice/chatSlice";
import StoryViewer from "../Home/Story/ViewUserStory";
import ViewMyStory from "../Home/Story/ViewMyStory";
import { hideModal, showModal } from "../store/Slice/modalSlice";
import toast from "react-hot-toast";
import { useGetAllStoryQuery } from "../store/api/GetStoryByUser";
import { setReelId } from "../store/Slice/ReelIdSlice";
import { setSelectedReelId } from "../store/Slice/selectedReelIdSlice";
import { IoMdAddCircleOutline } from "react-icons/io";
import { AiOutlineFilePdf } from "react-icons/ai";
import OpenVideo from "./OpenVideoComponent";
import RoundedShimmer from "../components/RoundedShimmer";
import { setPostId } from "../store/Slice/PostIdSlice";
import { setSelectedPostId } from "../store/Slice/selectedPostIdSlice";
import PostDetail from "../Explore/Post_Detail";
import { setUserId } from "../store/Slice/SetUserIdForChatOpen";
import { ClipLoader } from "react-spinners";
import { setMessageList } from "../store/Slice/messageSlice";
import ReelDetail from "../Explore/Reel_Comment";
import { socketInstance } from "../utils/socket";
import TextTranslate from "../utils/TextTranslate";
import { showErrorToast } from "../components/Toast/ErrorToast";

function MessageList() {
  const MessageListArray = useAppSelector((state) => state.message.messagelist);
  const selectedUser = useAppSelector((state) => state.chat.selectedUser);
  const chatList = useAppSelector((state) => state.chatUser.chatlist);
  console.log("MessageListArray #$@12", MessageListArray);
  const { postData } = useApiPost();
  const [showScrollButton, setShowScrollButton] = useState(false);
  const [isLoading, setLoading] = useState(false);
  const [openImage, setOpenImage] = useState(false);
  const [groupedMessages, setGroupedMessages] = useState<any[]>([]);
  const bottomRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const dispatch = useAppDispatch();

  const newUser = useAppSelector((state) => state.newUserId.newUser);
  console.log("New User @@12", newUser);
  const lastFetchedUserId = useRef<string | null>(null);
  const activeUser = newUser?.id
    ? {
      second_id: newUser.id,
      first_name: newUser.first_name || "",
      profile_pic: newUser.profile_pic || "",
    }
    : selectedUser;

  // Function to update chat list order when sending/receiving messages
  const updateChatListWithNewMessage = (userId: string, messageData: any) => {
    // Find the user in current chat list
    const existingUserIndex = chatList.findIndex(
      (user: any) => user.second_id?.toString() === userId?.toString()
    );

    if (existingUserIndex !== -1) {
      // User exists, update their last message and move to top
      const updatedUser = {
        ...chatList[existingUserIndex],
        message: messageData.message || messageData.type,
        last_message_created: messageData.created_at || new Date().toISOString(),
        time: messageData.created_at || new Date().toISOString(),
        message_type: messageData.type,
        type: messageData.type,
        url: messageData.url || "",
      };

      // Remove user from current position and add to top
      const newChatList = [updatedUser, ...chatList.filter((_: any, i: number) => i !== existingUserIndex)];
      dispatch(updateChatListOrder(newChatList));
    } else if (messageData.from_user?.toString() === userId?.toString() || 
               messageData.to_user?.toString() === userId?.toString()) {
      // This is a new conversation, we need to fetch the user details
      const fetchNewUserDetails = async () => {
        try {
          const response = await postData("/user_details", {
            user_id: userId,
          });
          if (response?.user_data) {
            const newUserData = {
              second_id: userId,
              first_name: response.user_data.first_name || "",
              profile_pic: response.user_data.profile_pic || "",
              last_name: response.user_data.last_name || "",
              username: response.user_data.username || "",
              id: response.user_data.id,
              user_id: userId,
              my_id: Cookies.get("USERID"),
              last_seen: "",
              message: messageData.message || messageData.type,
              message_type: messageData.type,
              type: messageData.type,
              time: messageData.created_at || new Date().toISOString(),
              date: "",
              unread_message: "0",
              role: "",
              url: messageData.url || "",
              last_message_created: messageData.created_at || new Date().toISOString(),
            };
            
            // Add new user to top of chat list
            const newChatList = [newUserData, ...chatList];
            dispatch(updateChatListOrder(newChatList));
          }
        } catch (error) {
          console.error("Error fetching user details:", error);
        }
      };
      fetchNewUserDetails();
    }
  };

  useEffect(() => {
    if (newUser?.id && newUser.id !== selectedUser?.second_id) {
      dispatch(
        updateSelectedUser({
          second_id: newUser.id,
          first_name: newUser.first_name || "",
          profile_pic: newUser.profile_pic || "",
        })
      );
    }
  }, [newUser?.id]);

  useEffect(() => {
    if (newUser && selectedUser?.second_id === newUser.id) {
      dispatch(clearNewUser());
    }
  }, [selectedUser?.second_id, newUser?.id]);

  console.log("second Id @123", selectedUser?.second_id);

  useEffect(() => {
    if (!activeUser?.second_id) return;
    const myId = Cookies.get("USERID")?.toString();

    const filteredMessages = MessageListArray.filter(
      (msg) =>
        (msg.from_user?.toString() === myId &&
          msg.to_user?.toString() === activeUser.second_id?.toString()) ||
        (msg.from_user?.toString() === activeUser.second_id?.toString() &&
          msg.to_user?.toString() === myId)
    );

    setMessageList(filteredMessages);
  }, [MessageListArray, activeUser?.second_id]);

  console.log("Selected User @#414", newUser);
  useEffect(() => {
    if (!activeUser?.second_id) return;

    const fetchMessages = async () => {
      dispatch(setMessageList([]));

      if (lastFetchedUserId.current === activeUser.second_id) return;

      setLoading(true);
      try {
        const response = await postData("/new_message_list", {
          to_user: activeUser.second_id,
        });

        if (response?.chat) {
          dispatch(setMessageList(response.chat.reverse()));
          lastFetchedUserId.current = activeUser.second_id;
        }
      } catch (error) {
        console.error("Error fetching message list:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchMessages();
  }, [activeUser?.second_id]);

  console.log("Message List Array @#12", MessageListArray);

  useEffect(() => {
    const myId = Cookies.get("USERID")?.toString();
    if (!MessageListArray.length || !activeUser?.second_id || !myId) return;

    const filteredMessages = MessageListArray.filter(
      (msg) =>
        (msg.from_user?.toString() === myId &&
          msg.to_user?.toString() === activeUser.second_id?.toString()) ||
        (msg.from_user?.toString() === activeUser.second_id?.toString() &&
          msg.to_user?.toString() === myId)
    );

    console.log("Filtered for grouping:", filteredMessages);

    if (filteredMessages.length === 0) {
      setGroupedMessages([]);
      return;
    }

    const grouped = filteredMessages.reduce((acc: any, msg) => {
      const messageDate = new Date(msg.created_at);
      const dateString = new Intl.DateTimeFormat("en-GB", {
        day: "2-digit",
        month: "long",
        year: "numeric",
      }).format(messageDate);

      if (!acc[dateString]) {
        acc[dateString] = [];
      }
      acc[dateString].push(msg);
      return acc;
    }, {});

    setGroupedMessages(
      Object.entries(grouped).map(([date, msgs]) => ({ date, msgs }))
    );
  }, [MessageListArray, activeUser?.second_id]);

  console.log("Message 123@@@ 90", activeUser);

  const scrollToBottom = () => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [MessageListArray]);

  useEffect(() => {
    const handleScroll = () => {
      if (!containerRef.current) return;
      const { scrollTop, scrollHeight, clientHeight } = containerRef.current;

      const atBottom = scrollHeight - scrollTop - clientHeight < 100;
      setShowScrollButton(!atBottom);
    };

    const container = containerRef.current;
    container?.addEventListener("scroll", handleScroll);
    return () => container?.removeEventListener("scroll", handleScroll);
  }, []);

  const [url, setUrl] = useState("");
  const handleOpenImage = (url: string) => {
    setUrl(url);
    dispatch(showModal("OpenImageFromChat"));
  };

  const handleOpenVideo = (url: string) => {
    setUrl(url);
    dispatch(showModal("OpenVideoFromChat"));
  };

  const [selectUserId, setSelectedUserId] = useState("");
  const router = useRouter();
const handleUsernameClick = async (user: any) => {
  if (!user?.second_id) {
    console.error("User ID missing:", user);
    showErrorToast("Unable to open profile");
    return;
  }

  try {
    const response = await postData("/second_user_profile", {
      to_user_id: user.second_id,
    });

    const username = response?.user_data?.username;

    if (username) {
      router.push(`/Profile/${username}`);
    } else {
      console.error("Username not found:", user.second_id);
      showErrorToast("Unable to open profile");
    }
  } catch (error) {
    console.error("Error fetching profile:", error);
    showErrorToast("Unable to open profile");
  }
};

  console.log("New User Id 123", newUser?.id);
  console.log("Selected User Id 123", selectedUser?.second_id);
  const MyUserId = Cookies.get("USERID");

  const [userIndex, setUserIndex] = useState(0);
  const [storyIndex, setStoryIndex] = useState(0);
  const isViewOtherUserStoryModalVisible = useAppSelector(
    (state) => state.modals.ViewOtherUsersStory
  );

  const isOpenVideoModalVisible = useAppSelector(
    (state) => state.modals.OpenVideoFromChat
  );
  const isOpenImageModalVisible = useAppSelector(
    (state) => state.modals.OpenImageFromChat
  );

  const token = Cookies.get("Snapta_auth_token");
  const { data: AllUsersStory, refetch } = useGetAllStoryQuery({
    token: token || "",
  });
  const storyData = AllUsersStory?.story || [];
  const myStoryData = AllUsersStory?.my_post;
  const handleOpenUserStory = (userId: string, storyId: string) => {
    let userIndex = -1;
    let userStoryList = [];


if (userId === MyUserId) {
  // Use optional chaining and nullish coalescing to ensure a number is returned
  userIndex = myStoryData?.findIndex(
    (user) => user.user_id?.toString() === userId.toString()
  ) ?? -1;

  // 2. Perform the safety check
  if (userIndex === -1 || !myStoryData) {
    showErrorToast("Your story not found.", "Something went wrong.");
    return;
  }

  // Now TypeScript knows userIndex is definitely a number and not -1
  userStoryList = myStoryData[userIndex].story_image || [];
} else {
      userIndex = storyData?.findIndex(
        (user) => user.user_id?.toString() === userId.toString()
      );

      if (userIndex === -1) {
        showErrorToast("User story not found.","Something went wrong.");
        return;
      }

      userStoryList = storyData[userIndex]?.story_image || [];
    }

    const storyIndex = userStoryList.findIndex(
      (story) => story.story_id?.toString() === storyId.toString()
    );

    if (storyIndex === -1) {
      showErrorToast("Story not found or may have expired.");
      return;
    }

    setUserIndex(userIndex);
    setStoryIndex(storyIndex);

    if (userId === MyUserId) {
      dispatch(showModal("ViewStory"));
    } else {
      dispatch(showModal("ViewOtherUsersStory"));
    }
  };

  const isMyStoryModalVisible = useAppSelector(
    (state) => state.modals.ViewStory
  );
  function OpenViewStory() {
    dispatch(showModal("ViewStory"));
  }

  const viewReel = (reelId: string) => {
    dispatch(setSelectedReelId(reelId));
    router.push("/Reels");
  };

  console.log("My story @1##$gfhg", userIndex);

  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);
  const handleImageClick = (postId: string, images: string[]) => {
    setSelectedPost({ postId, images });
  };
  console.log("Messages #$%$%123", selectedUser);

  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
    index: number;
  } | null>(null);

  const handleVideoClick = (postId: string, url: string, index: number) => {
    setSelectedVideo({ postId, url, index });
    dispatch(showModal("ReelDetail"));
  };

  useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [groupedMessages]);

  const socket = socketInstance();

  // Listen for new messages and update the chat list
  useEffect(() => {
    const handleNewMessage = (newMessage: any) => {
      const myUserId = Cookies.get("USERID");

      // Play sound for incoming messages
      if (newMessage?.from_user?.toString() !== myUserId) {
        const audio = new Audio("/audio/achive-sound-132273.mp3");
        audio.play().catch((err) => {
          console.warn("Sound play failed:", err);
        });
      }

      // Determine the other user in the conversation
      const otherUserId = newMessage?.from_user?.toString() === myUserId 
        ? newMessage?.to_user?.toString() 
        : newMessage?.from_user?.toString();

      // Update chat list order with the new message
      if (otherUserId) {
        updateChatListWithNewMessage(otherUserId, newMessage);
      }

      // If the new message is from or to the current selected user, refresh messages
      if (selectedUser && (newMessage?.from_user?.toString() === selectedUser.second_id?.toString() ||
          newMessage?.to_user?.toString() === selectedUser.second_id?.toString())) {
        // Refetch messages for the current conversation
        const fetchUpdatedMessages = async () => {
          try {
            const response = await postData("/new_message_list", {
              to_user: selectedUser.second_id,
            });
            if (response?.chat) {
              dispatch(setMessageList(response.chat.reverse()));
            }
          } catch (error) {
            console.error("Error fetching updated messages:", error);
          }
        };
        fetchUpdatedMessages();
      }
    };

    socket.on("message", handleNewMessage);

    return () => {
      socket.off("message", handleNewMessage);
    };
  }, [selectedUser, postData, dispatch, chatList]);

  // Also update chat list when sending a message (you'll need to call this when sending)
  // You can add this to your send message function
  const onMessageSend = (sentMessage: any) => {
    const myUserId = Cookies.get("USERID");
    const otherUserId = sentMessage?.to_user?.toString();
    
    if (otherUserId) {
      updateChatListWithNewMessage(otherUserId, sentMessage);
    }
  };

  return (
    <>
      {selectedUser ? (
        <>
          <div
            className="flex-1 overflow-y-auto overflow-x-hidden px-4 py-2 space-y-4 bg-[var(--bg-primary)] webkit-scrollbar"
            ref={containerRef}
          >
            <div className="rounded-full place-items-center pt-10 ">
              {isLoading ? (
                <>
                  <div className="w-24 h-24">
                    <RoundedShimmer />
                  </div>
                </>
              ) : (
                <>
                  <img
                    src={selectedUser?.profile_pic}
                    className="w-24 h-24 rounded-full border border-[var(--border-color)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                    alt="profile"
                  />
                </>
              )}

              <h2 className="text-[var(--text-primary)] font-gilroy_bold text-lg font-semibold pt-4 pb-1">
                {selectedUser?.first_name}
              </h2>
             <button
  className="bg-[var(--bg-secondary)] text-[var(--text-primary)] flex justify-center font-gilroy_semibold rounded-[5px] text-[13px] px-4 py-1 font-medium"
  onClick={() => handleUsernameClick(selectedUser)}
>
  <TextTranslate text="View Profile" />
</button>
            </div>
            {isLoading ? (
              <>
                <div className="py-20 flex place-items-center justify-center">
                  <ClipLoader color="#452B7A" size={15} loading={isLoading} />
                </div>
              </>
            ) : (
              <>
                {groupedMessages.map((group, index) => {
                  const validMessages = group.msgs?.filter((msg: { url: any; type: string; message: string; }) => {
                    if (
                      !msg.url &&
                      ["image", "video", "file", "post", "reel", "story", "story_reply"].includes(msg.type)
                    ) {
                      return false;
                    }
                    if (msg.type === "text" && (!msg.message || msg.message.trim() === "")) {
                      return false;
                    }
                    return true;
                  });

                  if (!validMessages || validMessages.length === 0) return null;

                  const isOnlyEmoji = (text: string) => {
                    const emojiRegex =
                      /^(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D\p{Extended_Pictographic})*|\s)+$/u;
                    return emojiRegex.test(text.trim());
                  };

                  return (
                    <div key={index}>
                      <div className="text-center text-[11px] text-[#808080] font-semibold py-2">
                        {group.date}
                      </div>

                      {validMessages.map((msg, index) => {
                        const isMyMessage = msg.from_user == MyUserId;

                        return (
                          <div
                            key={index}
                            className={`w-full flex ${isMyMessage ? "justify-end" : "justify-start"
                              } mb-2 md:pl-3 md:pr-2`}
                          >
                            <div className="flex flex-col items-start gap-0.5">
                              <div
                                className={`flex items-end gap-2 max-w-xs ${isMyMessage
                                    ? "flex-row"
                                    : "flex-row-reverse self-start"
                                  }`}
                              >
                                {/* Text */}
                                {msg.type === "text" && msg.message && (
                                  <div
                                    className={`font-gilroy_regular ${isOnlyEmoji(msg.message)
                                        ? "text-4xl leading-none"
                                        : `px-3 py-1 text-white text-sm ${isMyMessage
                                          ? "bg-[#8C5EE7] rounded-t-lg rounded-bl-lg"
                                          : "bg-[#636168] rounded-t-lg rounded-br-lg"
                                        }`
                                      }`}
                                  >
                                    {msg.message}
                                  </div>
                                )}

                                {/* Image */}
                                {msg.type === "image" && (
                                  <img
                                    src={msg.url}
                                    className="w-48 h-56 object-contain rounded-xl border border-white/15 cursor-pointer"
                                    alt="image"
                                    onClick={() => handleOpenImage(msg.url!)}
                                  />
                                )}

                                {/* File */}
                                {msg.type === "file" && (
                                  <a
                                    href={msg.url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex items-center gap-2 bg-[var(--border-color)] p-2 rounded-lg transition place-items-center"
                                  >
                                    <AiOutlineFilePdf className="text-red-600 w-5 h-5" />
                                    <p className="text-sm truncate font-gilroy_semibold ">
                                      {msg.url.split("/").pop()}
                                    </p>
                                  </a>
                                )}

                                {/* Video */}
                                {msg.type === "video" && (
                                  <div className="relative">
                                    <img
                                      src={msg.video_thumbnail}
                                      className="w-48 h-56 object-cover rounded-xl border border-white/15 cursor-pointer"
                                      onClick={() => handleOpenVideo(msg.url)}
                                    />
                                    <div className="absolute inset-0 flex justify-center items-center">
                                      <button
                                        className="p-4 bg-black bg-opacity-50 backdrop-blur-md rounded-full"
                                        onClick={() => handleOpenVideo(msg.url)}
                                      >
                                        <img
                                          src={"/assets/play.png"}
                                          alt="play_pause"
                                          height={20}
                                          width={20}
                                        />
                                      </button>
                                    </div>
                                  </div>
                                )}

                                {/* Story Reply */}
                                {msg.type === "story_reply" && (
                                  <div className="flex flex-col w-[200px]">
                                    <p className="text-xs font-gilroy_regular text-[#B5B5B5]">
                                      You replied to story
                                    </p>
                                    <div
                                      className={` border rounded-t-xl ${isMyMessage
                                          ? "bg-[#8C5EE7] rounded-bl-lg border-[#8C5EE7]"
                                          : "bg-[#54505B] rounded-br-lg border-[#54505B]"
                                        }`}
                                    >
                                      <div
                                        className="h-[200px] cursor-pointer"
                                        onClick={() =>
                                          handleOpenUserStory(msg.post_user_id, msg.story_id)
                                        }
                                      >
                                        <img
                                          src={msg.url}
                                          className="w-full h-full object-cover rounded-xl"
                                        />
                                      </div>
                                      <p className="text-xs font-gilroy_md p-1 text-[#FFFFFF]">
                                        {msg.message}
                                      </p>
                                    </div>
                                  </div>
                                )}

                                {/* Post */}
                                {msg.type === "post" && msg.url && (
                                  <div
                                    className={`w-48 h-auto overflow-hidden relative rounded-t-lg p-1 cursor-pointer ${isMyMessage
                                        ? "bg-[#8C5EE7] rounded-bl-lg"
                                        : "bg-[#54505B] rounded-br-lg"
                                      }`}
                                    onClick={() => handleImageClick(msg.post_id, [msg.url])}
                                  >
                                    <div className="cursor-pointer">
                                      <img
                                        src={msg.url}
                                        alt="post"
                                        className="w-full h-56 object-cover rounded-lg"
                                      />
                                      <div className="absolute top-2 left-2 flex gap-2 items-center">
                                        <img
                                          src={msg.post_user_profile_pic}
                                          alt="user"
                                          className="w-6 h-6 rounded-full"
                                        />
                                        <p className="text-white text-sm font-gilroy_semibold">
                                          {msg.post_user_name}
                                        </p>
                                      </div>
                                    </div>
                                    <p className="mt-1 text-white text-sm line-clamp-2">
                                      {msg.post_text}
                                    </p>
                                  </div>
                                )}

                                {/* Reel */}
                                {msg.type === "reel" && msg.url && (
                                  <div
                                    className={`relative w-48 h-58 rounded-t-lg rounded-bl-lg overflow-hidden cursor-pointer p-1 ${isMyMessage ? "bg-[#8C5EE7]" : "bg-[#54505B]"
                                      }`}
                                    onClick={() =>
                                      handleVideoClick(msg.reel_id, msg.url, index)
                                    }
                                  >
                                    <div className="relative">
                                      <img
                                        src={msg.video_thumbnail}
                                        alt="reel"
                                        className="w-full h-64 object-cover rounded-lg"
                                      />
                                      <div
                                        className={`absolute bottom-0 ${isMyMessage
                                            ? "rounded-full -bottom-1 -right-1 bg-[#8C5EE7] p-0.5"
                                            : "-left-1 p-0.5 -bottom-1 rounded-full bg-[#54505B]"
                                          }`}
                                      >
                                        <img
                                          src="/assets/reel_icon.png"
                                          alt="Reel Icon"
                                          className="w-5 h-5 rounded-full pt-0.5 pr-0.5"
                                        />
                                      </div>
                                    </div>

                                    <div className="absolute top-2 left-2 flex gap-2 items-center">
                                      <img
                                        src={msg.post_user_profile_pic}
                                        alt="user"
                                        className="w-6 h-6 rounded-full"
                                      />
                                      <p className="text-white text-sm font-gilroy_semibold">
                                        {msg.post_user_name}
                                      </p>
                                    </div>
                                  </div>
                                )}

                                {/* Story */}
                                {msg.type === "story" && msg.url && (
                                  <div
                                    className="relative w-48 h-56 rounded-xl overflow-hidden cursor-pointer"
                                    onClick={() =>
                                      handleOpenUserStory(msg.post_user_id, msg.story_id)
                                    }
                                  >
                                    <img
                                      src={msg.url}
                                      alt="post"
                                      className="w-full h-full object-cover"
                                    />
                                    <div className="absolute top-2 left-2 flex gap-2 items-center">
                                      <img
                                        src={msg.post_user_profile_pic}
                                        alt="user"
                                        className="w-6 h-6 rounded-full"
                                      />
                                      <p className="text-white text-sm font-gilroy_semibold">
                                        {msg.post_user_name}
                                      </p>
                                    </div>
                                  </div>
                                )}

                                {/* Profile Pic */}
                                <img
                                  src={
                                    isMyMessage
                                      ? msg.profile_pic
                                      : selectedUser?.profile_pic
                                  }
                                  className="w-5 h-5 rounded-full object-cover border border-[var(--border-color)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                                  alt="profile"
                                />
                              </div>

                              {/* Time */}
                              <span
                                className={`text-[11px] text-[#707070] font-gilroy_regular ${isMyMessage ? "self-end pr-7" : "self-start pl-7"
                                  }`}
                              >
                                {formatTimeSimple(msg.created_at)}
                              </span>
                            </div>
                          </div>
                        );
                      })}

                      <div ref={bottomRef}></div>
                    </div>
                  );
                })}
              </>
            )}
          </div>
          {showScrollButton && (
            <button
              className="absolute bottom-20 left-1/2 transform -translate-x-1/2 bg-[var(--bg-secondary)] p-2 rounded-full shadow-lg"
              onClick={scrollToBottom}
            >
              <BsChevronDown className="text-[var(--text-primary)]" />
            </button>
          )}
        </>
      ) : (
        <>
          <div className="flex flex-col items-center justify-center min-h-screen bg-[var(--bg-primary)]">
            <img src="/assets/NoPost.png" className="w-16 h-16" />
            <h2 className="text-base font-semibold text-[var(--text-primary)]">
              <TextTranslate text="No conversations yet" />
            </h2>
            <h2 className="text-base font-semibold text-[var(--text-primary)]">
              <TextTranslate text="Start your conversation" />
            </h2>
          </div>
        </>
      )}

      {isOpenImageModalVisible && <OpenImage url={url} />}
      {isViewOtherUserStoryModalVisible && (
        <StoryViewer
          initialUserIndex={userIndex}
          initialStoryIndex={storyIndex}
        />
      )}
      {selectedPost && (
        <PostDetail
          
          images={selectedPost.images}
          postId={selectedPost.postId}
          onClose={() => setSelectedPost(null)}
        />
      )}

      {selectedVideo && (
        <ReelDetail
          videoSrc={selectedVideo.url}
          postId={selectedVideo.postId}
          onClose={() => {
            setSelectedVideo(null);
            dispatch(hideModal("ReelDetail"));
          } } isMuted={false} onMuteToggle={function (isMuted: boolean): void {
            throw new Error("Function not implemented.");
          } } onCommentSuccess={function (): void {
            throw new Error("Function not implemented.");
          } }        />
      )}

      {isOpenVideoModalVisible && <OpenVideo url={url} />}
      {isMyStoryModalVisible && <ViewMyStory />}
    </>
  );
}

export default MessageList;