import { useEffect, useState } from "react";
import { BsCameraVideo } from "react-icons/bs";
import { IoImageOutline, IoLocationOutline } from "react-icons/io5";
import chatSidebarTime from "../../../utils/chatSidebarTime";
import { OuterChat } from "../../../types/ChatListType";
import { HiOutlineDocumentText } from "react-icons/hi";

import {
  ContextMenu,
  ContextMenuTrigger,
  ContextMenuItem,
} from "rctx-contextmenu";
import { socketInstance } from "../../../socket/socket";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { updateCurrentConversation } from "../../../store/Slices/CurrentConversationSlice";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { BlockUserRes } from "../../../types/ResType";
import useApiPost from "../../../hooks/PostData";
import toast from "react-hot-toast";
import CallInConversationList from "./CallInConversationList";
import { RiContactsLine } from "react-icons/ri";
import { PulseLoader } from "react-spinners";
import { Menu, MenuButton, MenuItems, MenuItem } from "@headlessui/react";
import { IoIosArrowDown } from "react-icons/io";
import TextTranslate from "../../../utils/TextTranslate";
import { updateMessageOptions } from "../../../store/Slices/MessageOptionsSlice";
import { useNavigateToChat } from "../../../hooks/useNavigateToChat";
import { useTranslateText } from "../../../hooks/useTranslateText";
import SearchNotFoundAnimation from "../../../components/SearchNotFoundAnimation";

export default function ArchiveConversationList({
  searchUser,
}: {
  searchUser: string;
}) {
  const { postData } = useApiPost();
  // useEffect(() => {
  //   socketInstance().emit("archived_chat_list", {});
  // }, []);
  const dispatch = useAppDispatch();
  const translate = useTranslateText();
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const TypingUserList = useAppSelector((state) => state.TypingUserList);
  const archiveList = useAppSelector((state) => state.archiveList);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );

  const user_id = useAppSelector((state) => state.userData.user_id);

  const navigateToChat = useNavigateToChat();
  const [SelectedConversation, setSelectedConversation] = useState<OuterChat>();

  async function blockUser() {
    const is_block = SelectedConversation?.Records[0].blocked_by.includes(
      user_id.toString(),
    );
    dispatch(
      updateMessageOptions({
        showModal: true,
        modalName: "block_user",
        title: `Are you sure you want to ${is_block ? "unblock" : "block"} ${SelectedConversation?.PeerUserData.full_name}`,
        description: is_block
          ? "After unblocking, you will receive messages from this user."
          : "After blocking, you will not receive any messages from this user.",
      }),
    );
  }

  async function unArchiveConversation() {
    socketInstance().emit("archive_chat", {
      chat_id: SelectedConversation?.Records[0].chat_id,
    });
    // socketInstance().emit("ChatList", {});
    toast.success(translate("Conversation Unarchived"), { position: "bottom-left" });
  }

  async function deleteConversation() {
    sessionStorage.setItem(
      "selectedConversation",
      JSON.stringify(SelectedConversation),
    );
    dispatch(
      updateMessageOptions({
        showModal: true,
        modalName: "delete_conversation",

        title: `Are you sure you want to delete chat of ${SelectedConversation?.Records[0].chat_type == "group" ? SelectedConversation?.Records[0].group_name : SelectedConversation?.PeerUserData.full_name}?`,
        description: "This action cannot be undone.",
      }),
    );
  }

  const handleBlockContextMenu = (e: OuterChat) => {
    e;
  };

  return (
    <>
      <div className="flex h-[80vh] w-full flex-col overflow-y-auto overflow-x-hidden lg:max-w-md">
        {archiveList.Chats.length == 0 ? (
          <div className="grid h-96 place-content-center gap-5">
            <SearchNotFoundAnimation />
            <div>{translate("No Conversations Found")}</div>
          </div>
        ) : (
          archiveList.Chats.filter(
            (chat) =>
              chat.PeerUserData.full_name
                .toLowerCase()
                .includes(searchUser.toLowerCase()) ||
              chat.Records[0].group_name
                .toLowerCase()
                .includes(searchUser.toLowerCase()),
          ).map((e) => {
            return (
              <>
                <ContextMenuTrigger id="my-context-menu-2">
                  <div
                    onClick={() => {
                      navigateToChat({
                        chat_id: e.Records[0].chat_id,
                        chat_type: e.Records[0].chat_type,
                        full_name: e.PeerUserData.full_name,
                        group_name: e.Records[0].group_name,
                        group_icon: e.Records[0].group_icon,
                        profile_pic: e.PeerUserData.profile_pic,
                        user_id: e.PeerUserData.user_id,
                        is_group_blocked: e.Records[0].blocked_by.includes(
                          user_id.toString(),
                        ),
                        user_name: e.PeerUserData.user_name,
                        email_id: e.PeerUserData.email,
                        unseen_count: e.Records[0].unseen_count,
                        updatedAt: e.PeerUserData.updatedAt!,
                        is_message_list_empty:
                          e.Records[0].Messages.length === 0,
                        createdAt: e.Records[0].createdAt,
                        bio: e.PeerUserData.bio,
                        group_description: e.Records[0].group_description,
                        mobile_num: e.PeerUserData.mobile_num!,
                        is_archived: true,
                      });
                    }}
                    onContextMenu={() => {
                      setSelectedConversation(e);
                    }}
                    className={`group flex cursor-pointer items-center px-3 py-4 hover:bg-selectedChat ${currentConversationData.chat_id == e.Records[0].chat_id && "bg-selectedChat"}`}
                  >
                    <div className="relative mr-3 h-12 w-12">
                      <LoadingSkeletonImageDynamic
                        radius=""
                        className="h-12 w-12 rounded-full object-cover"
                        image_height="100%"
                        image_url={
                          e.Records[0].chat_type == "group"
                            ? e.Records[0].group_icon
                            : e.PeerUserData.profile_pic
                        }
                        image_width=""
                      />
                      {e.Records[0].chat_type == "private" &&
                        OnlineUserList.onlineUsers.find(
                          (user) => user.user_id == e.PeerUserData.user_id,
                        ) && (
                          <img
                            className="absolute bottom-0 right-0 z-30 h-4 w-4"
                            src="/Home/Online_Green_dot.png"
                            alt=""
                          />
                        )}
                    </div>
                    {/* <img
                    src={e.is_group ? e.group_profile_image : e.profile_image}
                    className="mr-3 h-10 w-10 rounded-full object-cover 2xl:h-12 2xl:w-12"
                    alt=""
                  /> */}
                    <div>
                      <div className="text-base font-medium capitalize text-darkText">
                        {e.Records[0].chat_type == "group"
                          ? e.Records[0].group_name
                          : e.PeerUserData.user_name}
                      </div>

                      <div className="flex items-center gap-x-1">
                        {/* <LiaCheckDoubleSolid className="text-lg text-primary" /> */}
                        <div className="line-clamp-1 flex w-full max-w-[12.5rem] gap-x-1 text-[13px] text-lightText">
                          {/* First check for typing ====================================================================================*/}
                          <>
                            {TypingUserList.typingUserList.some(
                              (typing) =>
                                typing.chat_id == e.Records[0].chat_id,
                            ) ? (
                              <div className="flex items-center">
                                {/* <div className="text-[#FDD030] mr-2">Typing</div> */}
                                <PulseLoader
                                  speedMultiplier={0.85}
                                  color="#FDD030"
                                  size={8}
                                />
                              </div>
                            ) : (
                              e.Records[0].Messages.length > 0 && (
                                <>
                                  {e.Records[0].Messages[0].message_type ==
                                  "image" ? (
                                    <>
                                      <IoImageOutline className="fa fa-solid fa-image w-5 text-xl text-gray-500" />{" "}
                                      Image
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "gif" ? (
                                    <>
                                      😈
                                      <div>Gif</div>
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "video" ? (
                                    <>
                                      <BsCameraVideo className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                                      Video
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "doc" ? (
                                    <>
                                      <HiOutlineDocumentText className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                                      Document
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "location" ? (
                                    <>
                                      <IoLocationOutline className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                                      Location
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "text" ? (
                                    <span className="line-clamp-1 w-full">
                                      {e.Records[0].Messages[0].message_content}
                                    </span>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "link" ? (
                                    <>
                                      <span>🔗</span>
                                      <span className="line-clamp-1 w-full">
                                        {
                                          e.Records[0].Messages[0]
                                            .message_content
                                        }
                                      </span>
                                    </>
                                  ) : e.Records[0].Messages[0].message_type ==
                                    "contact" ? (
                                    <div className="flex items-center gap-1">
                                      <RiContactsLine />
                                      <span className="line-clamp-1">
                                        Contact
                                      </span>
                                    </div>
                                  ) : e.Records[0].Messages[0].message_type ==
                                      "video" ||
                                    e.Records[0].Messages[0].message_type ==
                                      "audio" ? (
                                    <>
                                      <CallInConversationList messageData={e} />
                                    </>
                                  ) : (
                                    <>
                                      {e.Records[0].Messages[0].message_content}
                                    </>
                                  )}
                                </>
                              )
                            )}
                          </>
                        </div>
                      </div>
                    </div>

                    <div className="ml-auto grid h-full grid-cols-1 place-content-start gap-y-2 text-center">
                      <div className="min-w-20 text-xs text-lightText">
                        {chatSidebarTime(
                          e.Records[0].Messages.length > 0
                            ? e.Records[0].Messages[0]?.updatedAt
                            : e.Records[0].updatedAt,
                        )}
                      </div>
                      <div className="mx-auto flex w-fit gap-1">
                        {e.Records[0].unseen_count > 0 ? (
                          <div className="primary-gradient z-10 mx-auto grid h-5 w-5 place-content-center rounded-full text-xs text-white">
                            {e.Records[0].unseen_count}
                          </div>
                        ) : (
                          <>
                            <div className="h-5 w-5"></div>
                          </>
                        )}
                        {/* <div className="hidden group-hover:inline"> */}
                        <Menu>
                          <MenuButton
                            onClick={(event) => {
                              event.stopPropagation(); // Prevents the parent onClick event
                              setSelectedConversation(e);
                            }}
                            className="invisible items-center font-semibold shadow-2xl focus:outline-none group-hover:visible data-[focus]:outline-0"
                          >
                            <IoIosArrowDown className="cursor-pointer text-xl" />
                          </MenuButton>

                          <MenuItems
                            transition
                            anchor="bottom end"
                            className="z-10 w-52 origin-top-right rounded-xl border border-borderColor bg-modalBg p-1 text-sm/6 transition duration-200 ease-out [--anchor-gap:var(--spacing-1)] focus:outline-none data-[closed]:scale-95 data-[closed]:opacity-0"
                          >
                            <MenuItem>
                              <button
                                onClick={() => {
                                  unArchiveConversation();
                                }}
                                className="group flex w-full items-center gap-2 rounded-lg py-1.5 pl-6 data-[focus]:bg-dropdownOptionHover"
                              >
                                <TextTranslate text="Unarchive Chat" />
                              </button>
                            </MenuItem>
                            <MenuItem>
                              <button
                                onClick={() => {
                                  deleteConversation();
                                }}
                                className="group flex w-full items-center gap-2 rounded-lg py-1.5 pl-6 data-[focus]:bg-dropdownOptionHover"
                              >
                                <TextTranslate text="Delete Chat" />
                              </button>
                            </MenuItem>

                            {e.Records[0].chat_type != "group" && (
                              <MenuItem>
                                <button
                                  onClick={() => {
                                    blockUser();
                                  }}
                                  className="group flex w-full items-center gap-2 rounded-lg py-1.5 pl-6 data-[focus]:bg-dropdownOptionHover"
                                >
                                  <TextTranslate
                                    text={
                                      e.Records[0].blocked_by.includes(
                                        user_id.toString(),
                                      )
                                        ? "Unblock"
                                        : "Block"
                                    }
                                  />
                                </button>
                              </MenuItem>
                            )}
                          </MenuItems>
                        </Menu>
                        {/* </div> */}
                      </div>
                    </div>
                  </div>
                  <hr className="border-t border-borderColor" />
                </ContextMenuTrigger>
              </>
            );
          })
        )}
      </div>

      {SelectedConversation?.Records[0].chat_type != "group" ? (
        <ContextMenu id="my-context-menu-2" className="!rounded-xl !bg-modalBg">
          <ContextMenuItem
            onClick={() => {
              unArchiveConversation();
            }}
            className="hover:!bg-dropdownOptionHover"
          >
            <TextTranslate text="Unarchive Chat" />
          </ContextMenuItem>
          {/* <ContextMenuItem className="hover:!bg-dropdownOptionHover">
            Mute Notification
          </ContextMenuItem> */}
          <ContextMenuItem
            onClick={() => {
              deleteConversation();
            }}
            className="hover:!bg-dropdownOptionHover"
          >
            <TextTranslate text="Delete Chat" />
          </ContextMenuItem>
        </ContextMenu>
      ) : (
        <ContextMenu id="my-context-menu-2" className="!rounded-xl !bg-modalBg">
          <ContextMenuItem
            onClick={() => {
              unArchiveConversation();
            }}
            className="hover:!bg-dropdownOptionHover"
          >
            <TextTranslate text="Unarchive Chat" />
          </ContextMenuItem>
          {/* <ContextMenuItem className="hover:!bg-dropdownOptionHover">
            Mute Notification
          </ContextMenuItem> */}
          <ContextMenuItem
            onClick={() => {
              deleteConversation();
            }}
            className="hover:!bg-dropdownOptionHover"
          >
            <TextTranslate text="Delete Chat" />
          </ContextMenuItem>
          <ContextMenuItem
            onClick={() => {
              blockUser();
            }}
            className="hover:!bg-dropdownOptionHover"
          >
            <TextTranslate
              text={
                SelectedConversation?.Records[0].blocked_by.includes(
                  user_id.toString(),
                )
                  ? "Unblock"
                  : "Block"
              }
            />
          </ContextMenuItem>
        </ContextMenu>
      )}
    </>
  );
}
