import { PulseLoader } from "react-spinners";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import {
  setViewImage,
  toggleProfileView,
  updateViewState,
} from "../../../store/Slices/ViewManagerSlice";
import { formatLastSeen } from "../../../utils/formatUTCtoLocalDate";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { useConversationInfo } from "../../../store/api/useConversationInfo";
import { useEffect, useState } from "react";
import TextTranslate from "../../../utils/TextTranslate";
import { IoChevronBack } from "react-icons/io5";
import { resetCurrentConversation } from "../../../store/Slices/CurrentConversationSlice";
import ShowSavedName from "../../../components/ShowSavedName";
import { useConversationMembers } from "../../../store/api/useConversationMembers";
import { TypingUser } from "../../../store/Slices/TypingUserListSlice";

export default function Profile() {
  const dispatch = useAppDispatch();
  const [currentConversationTyping, setcurrentConversationTyping] = useState<
    TypingUser[]
  >([]);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const ContactList = useAppSelector((state) => state.ContactList);
  const [showLastSeen, setshowLastSeen] = useState(false);
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const TypingUserList = useAppSelector((state) => state.TypingUserList);
  const userData = useAppSelector((state) => state.userData);
  const { data: conversationMembers, isLoading } = useConversationMembers();
  useEffect(() => {
    setTimeout(() => {
      setshowLastSeen(true);
    }, 3000);
  }, []);
  // console.log(UserLastSeenList, "UserLastSeenList");

  useEffect(() => {
    setcurrentConversationTyping(
      TypingUserList.typingUserList.filter(
        (typing) => typing.chat_id == currentConversationData.chat_id,
      ),
    );
  }, [TypingUserList, currentConversationData.chat_id]);

  return (
    <div className="flex items-center sm:gap-2">
      {/* Back button ===========================================================*/}
      <IoChevronBack
        onClick={() => {
          dispatch(
            updateViewState({
              show_chats_sidebar: true,
            }),
          );
          dispatch(resetCurrentConversation());
        }}
        className="mr-2 flex w-fit cursor-pointer text-2xl lg:hidden"
      />

      <div
        onClick={() => {
          dispatch(
            setViewImage({
              show_image: true,
              image_src: [
                (currentConversationData.chat_type == "group"
                  ? currentConversationData.group_icon
                  : currentConversationData.profile_pic) ?? "",
              ],
            }),
          );
        }}
        className="mr-3 min-h-10 min-w-10 cursor-pointer overflow-hidden rounded-full 2xl:h-12 2xl:w-12"
      >
        <LoadingSkeletonImageDynamic
          radius=""
          className="min-h-10 min-w-10 object-cover 2xl:h-12 2xl:w-12"
          image_height="100%"
          image_url={
            (currentConversationData.chat_type == "group"
              ? currentConversationData.group_icon
              : currentConversationData.profile_pic) ?? ""
          }
          image_width=""
        />
      </div>
      <div className="flex flex-col">
        <div
          onClick={() => {
            dispatch(toggleProfileView(true));
          }}
          className="cursor-pointer text-sm font-medium capitalize text-darkText sm:text-base"
        >
          {currentConversationData.chat_type == "group" ? (
            currentConversationData.group_name
          ) : (
            <ShowSavedName
              user_id={currentConversationData.user_id!.toString()}
              name={currentConversationData.full_name}
            />
          )}
        </div>

        {currentConversationData.chat_type == "group" ? (
          <>
            {TypingUserList.typingUserList.find(
              (typing) => typing.chat_id == currentConversationData.chat_id,
            ) ? (
              <div className="flex items-center">
                <div className="mr-2 text-xs text-[#FDD030] sm:text-sm">
                  {!isLoading &&
                    currentConversationTyping &&
                    currentConversationTyping.length > 0 && (
                      <>
                        {currentConversationTyping
                          .map((typingUser) => {
                            // Find the corresponding user details from conversationInfo
                            const user =
                              conversationMembers?.data.Records?.find(
                                (user) =>
                                  user.User.user_id.toString() ===
                                  typingUser.user_id.toString(),
                              );

                            // Return the user name if found, otherwise return a fallback
                            return user
                              ? (ContactList?.data?.find(
                                  (e) =>
                                    e?.user_id.toString() ==
                                    user.User.user_id.toString(),
                                )?.name ?? user.User.full_name)
                              : "Unknown User"; // Fallback in case user is not found
                          })
                          .join(", ")}{" "}
                        {currentConversationTyping.length > 1 ? "are" : "is"}{" "}
                        typing...
                      </>
                    )}
                </div>
                {/* <PulseLoader speedMultiplier={0.85} color="#FDD030" size={8} /> */}
              </div>
            ) : (
              <div className="text-xs line-clamp-1 text-lightText sm:text-sm">
                {(() => {
                  const members = conversationMembers?.data?.Records || [];
                  const names = members.map(
                    (user) =>
                      user.user_id == userData.user_id
                        ? "You"
                        : ContactList?.data?.find(
                            (e) =>
                              e?.user_id.toString() ==
                              user.User.user_id.toString(),
                          )?.name ?? user.User.full_name,
                  );
                  const maxVisible = 3;
                  const visibleNames = names.slice(0, maxVisible).join(", ");
                  const remainingCount = names.length - maxVisible;

                  return (
                    <>
                      {visibleNames}
                      {remainingCount > 0 && (
                        <span
                          onClick={() => {
                            dispatch(toggleProfileView(true));
                          }}
                          className="cursor-pointer text-darkText"
                        >
                          {` +${remainingCount} More`}
                        </span>
                      )}
                    </>
                  );
                })()}
              </div>
            )}
          </>
        ) : (
          <>
            {TypingUserList.typingUserList.filter(
              (typing) => typing.chat_id == currentConversationData.chat_id,
            ).length != 0 ? (
              <div className="flex items-center">
                <div className="mr-2 text-xs text-[#FDD030] sm:text-sm">
                  Typing...
                </div>
                {/* <PulseLoader speedMultiplier={0.85} color="#FDD030" size={8} /> */}
              </div>
            ) : (
              <>
                {OnlineUserList.onlineUsers.find(
                  (user) => user.user_id == currentConversationData.user_id,
                ) ? (
                  <div className="flex items-center gap-2 text-xs sm:text-sm">
                    <img
                      className="h-3 w-3"
                      src="/Home/Online_Green_dot.png"
                      alt=""
                    />
                    <div>
                      <TextTranslate text="Online" />
                    </div>
                  </div>
                ) : showLastSeen ? (
                  <div className="text-xs text-lightText sm:text-sm">
                    {formatLastSeen(currentConversationData.updatedAt)}
                  </div>
                ) : (
                  ""
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}
