import { useState } from "react";
import { BsCameraVideo } from "react-icons/bs";
import { IoImageOutline, IoLocationOutline } from "react-icons/io5";
import chatSidebarTime from "../../../utils/chatSidebarTime";
import { HiOutlineDocumentText } from "react-icons/hi";
import { useAppSelector } from "../../../utils/hooks";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { ClipLoader } from "react-spinners";
import { RiContactsLine } from "react-icons/ri";
import CallInConversationList from "./CallInConversationList";
import { truncateSentence } from "../../../utils/truncateSentence";
import { CgPoll } from "react-icons/cg";
import { AiOutlineAudio } from "react-icons/ai";
import { OuterChat } from "../../../types/ChatListType";
import { useNavigateToChat } from "../../../hooks/useNavigateToChat";
import { useSearchChatList } from "../../../store/api/useSearchChatList";
import { Datum } from "../../../types/SearchChatListType";
import { useTheme } from "../../../context/ThemeProvider";
import SearchNotFoundAnimation from "../../../components/SearchNotFoundAnimation";

export default function SearchChatList({ searchUser }: { searchUser: string }) {
  const navigateToChat = useNavigateToChat();
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const user_id = useAppSelector((state) => state.userData.user_id);
  const { data: ChatListArray, isLoading } = useSearchChatList(searchUser);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const { theme } = useTheme();

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

  return (
    <>
      <div className="flex h-[80vh] w-full flex-col overflow-y-auto overflow-x-hidden lg:max-w-md">
        {isLoading ? (
          <div className="grid h-96 place-content-center gap-5">
            <ClipLoader color={theme == "dark" ? "#fff" : "#000"} size={20} />
          </div>
        ) : ChatListArray?.data?.length == 0 ? (
          <div className="grid h-96 place-content-center gap-5">
            {/* <img
              className="mx-auto h-16 w-16"
              src="/LightIcons/search_not_found.gif"
              alt=""
            /> */}
            <SearchNotFoundAnimation />
            <div>No Conversations Found</div>
          </div>
        ) : (
          ChatListArray?.data?.map((e: Datum) => {
            // if (e.Records[0].Messages.length == 0) {
            //   return null;
            // }
            const peerUser = e.participants.find(
              (user) => user.user_id != user_id,
            );
            return (
              <>
                <div
                  onClick={() => {
                    navigateToChat({
                      chat_id: e.chat_id,
                      chat_type: e.chat_type,
                      full_name: e.group_name,
                      group_name: e.group_name,
                      group_icon: e.group_icon,
                      profile_pic: e.group_icon,
                      user_id: peerUser?.user_id,
                      is_group_blocked: e.blocked_by.includes(
                        user_id.toString(),
                      ),
                      user_name: peerUser?.User.user_name,
                      updatedAt: e.updatedAt!,
                      is_message_list_empty: e.Messages.length === 0,
                      createdAt: e.createdAt,
                      bio: peerUser?.User.bio,
                      group_description: e.group_description,
                      mobile_num: peerUser?.User.mobile_num!,
                    });
                  }}
                  // onContextMenu={() => {
                  //   handleBlockContextMenu(e);
                  //   setSelectedConversation(e);
                  // }}
                  //   key={e.id}
                  key={e.chat_id}
                  className={`group flex cursor-pointer items-center px-3 py-4 hover:bg-selectedChat ${currentConversationData.chat_id == e.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.chat_type == "group"
                          ? e.group_icon
                          : peerUser?.User.profile_pic
                      }
                      image_width=""
                    />
                    {e.chat_type == "private" &&
                      OnlineUserList.onlineUsers.find(
                        (user) => user.user_id == peerUser?.User.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 className="min-w-44 sm:min-w-52 2xl:min-w-60">
                    <div className="line-clamp-1 text-base font-medium capitalize text-darkText">
                      {truncateSentence(
                        e.chat_type == "group"
                          ? e.group_name
                          : peerUser?.User.user_name,
                        32,
                      )}
                    </div>

                    <div className="flex items-center gap-x-1">
                      {/* <LiaCheckDoubleSolid className="text-lg text-primary" /> */}
                      <div className="line-clamp-1 flex w-full gap-x-1 text-[13px] text-lightText">
                        {/* First check for typing ====================================================================================*/}

                        <>
                          {e.cleared_for?.includes(user_id.toString()) ? (
                            ""
                          ) : e.Messages[0]?.message_type == "image" ? (
                            <>
                              <IoImageOutline className="fa fa-solid fa-image w-5 text-xl text-gray-500" />{" "}
                              Image
                            </>
                          ) : e.Messages[0]?.message_type == "gif" ? (
                            <>
                              😈
                              <div>Gif</div>
                            </>
                          ) : e.Messages[0]?.message_type == "video" ? (
                            <>
                              <BsCameraVideo className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                              Video
                            </>
                          ) : e.Messages[0]?.message_type == "audio" ? (
                            <>
                              <AiOutlineAudio className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                              Audio
                            </>
                          ) : e.Messages[0]?.message_type == "doc" ? (
                            <>
                              <HiOutlineDocumentText className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                              Document
                            </>
                          ) : e.Messages[0]?.message_type == "location" ? (
                            <>
                              <IoLocationOutline className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
                              Location
                            </>
                          ) : e.Messages[0]?.message_type == "text" ? (
                            <span className="w-full">
                              {/* {truncateSentence(
                                    "lorem impus kkks kdj ks good morning good evening",
                                    28,
                                  )} */}
                              {truncateSentence(
                                e.Messages[0]?.message_content,
                                32,
                              )}
                            </span>
                          ) : e.Messages[0]?.message_type == "link" ? (
                            <>
                              <span>🔗</span>
                              <span className="line-clamp-1 w-full">
                                {truncateSentence(
                                  e.Messages[0]?.message_content,
                                  32,
                                )}
                              </span>
                            </>
                          ) : e.Messages[0]?.message_type == "contact" ? (
                            <>
                              <RiContactsLine />
                              <span className="line-clamp-1">Contact</span>
                            </>
                          ) : e.Messages[0]?.message_type == "poll" ? (
                            <>
                              <CgPoll className="text-xl" />
                              <span className="line-clamp-1">Poll</span>
                            </>
                          ) : e.Messages[0]?.message_type == "video" ||
                            e.Messages[0]?.message_type == "audio" ? (
                            <>
                              <CallInConversationList messageData={e} />
                            </>
                          ) : (
                            <>{e.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-[5.5rem] text-xs text-lightText">
                      {chatSidebarTime(
                        e.Messages.length > 0
                          ? e.Messages[0]?.updatedAt
                          : e.updatedAt,
                      )}
                    </div>
                  </div>
                </div>
                <hr className="border-t border-borderColor" />
              </>
            );
          })
        )}
      </div>
    </>
  );
}
