/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { addOrRemoveUserId } from "../../../store/Slices/CreateGroupSlice";
import { useLocation, useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { useTheme } from "../../../context/ThemeProvider";
import { useGroupSettings } from "../../../store/api/useGroupSettings";
import toast from "react-hot-toast";
import TextTranslate from "../../../utils/TextTranslate";
import { updateViewState } from "../../../store/Slices/ViewManagerSlice";
import { useContactList } from "../../../store/api/useContactList";
import { ContactType } from "../../../types/ResType";
import { useNavigateToChat } from "../../../hooks/useNavigateToChat";
import { FaCircleCheck } from "react-icons/fa6";

export default function ContactList({ searchUser }: { searchUser: string }) {
  const { data: contactList, isLoading } = useContactList();
  const CreateGroup = useAppSelector((state) => state.CreateGroup);
  const userData = useAppSelector((state) => state.userData);
  const { data: groupSettingsData } = useGroupSettings();
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const ChatListArray = useAppSelector((state) => state.chatList);
  const dispatch = useAppDispatch();
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const navigate = useNavigate();
  const { theme } = useTheme();
  const location = useLocation();

  const navigateToChat = useNavigateToChat();

  function changeCurrentConversation(member: ContactType) {
    if (member.user_id == userData.user_id) {
      return;
    }
    const chatData = ChatListArray.Chats.find(
      (chatUser) =>
        chatUser.PeerUserData.user_id == member.user_id &&
        chatUser.Records[0].chat_type == "private",
    )?.Records[0];

    if (
      currentConversationData.chat_id == chatData?.chat_id &&
      currentConversationData.chat_id != 0
    ) {
      return;
    }

    navigateToChat({
      chat_id: chatData?.chat_id ?? -1,
      chat_type: "private",
      full_name: member.name!,
      group_name: "",
      group_icon: "",
      profile_pic: member.profile_pic!,
      user_id: member.user_id!,
      user_name: member.user_name!,
      unseen_count: 0,
      updatedAt: member.updatedAt,
      is_message_list_empty: chatData?.Messages?.length! <= 0 ? true : false,
      is_group_blocked: chatData?.blocked_by?.includes(
        userData.user_id.toString(),
      ),
      other_user_blocked_you:
        chatData?.blocked_by?.length &&
          chatData?.blocked_by.length >= 1 &&
          !chatData?.blocked_by.includes(userData.user_id.toString())
          ? true
          : false,
    });
  }

  return (
    <div className="my-3 flex h-[60vh] w-full max-w-full flex-col overflow-y-auto overflow-x-hidden pb-20">
      {isLoading ? (
        <div className="grid h-full place-content-center">
          <ClipLoader size={23} color={theme == "dark" ? "white" : "black"} />
        </div>
      ) : contactList?.data?.filter(
        (contact) => userData.user_id != contact?.user_id,
      ).length == 0 ? (
        <div className="grid h-96 place-content-center gap-5">
          <img
            className="mx-auto h-16 w-16"
            src="/LightIcons/contact_not_found_light.png"
            alt=""
          />
          <div className="px-5 text-center">
            Install the Whoxa mobile app first to sync your account and display
            your contacts here.
          </div>
        </div>
      ) : (
        contactList?.data
          .filter(
            (contact) =>
              contact.name.toLowerCase().includes(searchUser.toLowerCase()) &&
              userData.user_id != contact?.user_id,
          )
          .sort((a, b) => {
            const nameA = a?.name?.toLowerCase() || "";
            const nameB = b?.name?.toLowerCase() || "";
            return nameA.localeCompare(nameB);
          })
          .map((e) => {
            return (
              <>
                <div
                  onClick={() => {
                    if (location.pathname == "/contact-list") {
                      changeCurrentConversation(e);
                      dispatch(
                        updateViewState({
                          show_chats_sidebar: false,
                        }),
                      );
                      return;
                    }

                    if (
                      CreateGroup.user_id.length >=
                      Number(
                        groupSettingsData?.settings[0].max_members ?? 10,
                      ) &&
                      !CreateGroup.user_id.includes(e?.user_id)
                    ) {
                      toast.error(
                        `Max group memeber size is ${groupSettingsData?.settings[0].max_members ?? 10}`,
                        { position: "bottom-left" },
                      );
                      return;
                    }
                    dispatch(
                      addOrRemoveUserId({
                        user_id: e.user_id,
                      }),
                    );
                    //   if (
                    //     currentConversationData.chat_id != e.chat_id
                    //   ) {
                    //     dispatch(updateCurrentConversation(e));
                    //     dispatch(removeMessageList());
                    //   }
                  }}
                  onContextMenu={() => {
                    //   handleBlockContextMenu(e);
                    //   setSelectedConversation(e);
                  }}
                  //   key={e.id}
                  className={`flex cursor-pointer items-center px-3 py-4 hover:bg-selectedChat ${CreateGroup.user_id.includes(e?.user_id) && "bg-selectedChat"}`}
                >
                  <div className="relative mr-3 h-14 w-14 2xl:h-12 2xl:w-12">
                    <LoadingSkeletonImageDynamic
                      radius=""
                      className="min-h-12 min-w-12 rounded-full object-cover 2xl:h-12 2xl:w-12"
                      image_height="100%"
                      image_url={e?.profile_pic}
                      image_width=""
                    />
                    {OnlineUserList.onlineUsers.find(
                      (user) => user.user_id == e?.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?.name}
                      {/* <ShowSavedName user_id={e?.user_id} name={e?.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">
                        {e?.user_name}
                      </div>
                    </div>
                  </div>
                  {CreateGroup.user_id.includes(e?.user_id) && (
                    <div className="ml-auto grid h-full grid-cols-1 place-content-center gap-y-2 text-center">
                      {/* <img
                        className="h-5 w-5"
                        src="/Home/contact_selected.png"
                        alt=""
                      /> */}
                      <FaCircleCheck className="h-7 text-themeColor" />

                    </div>
                  )}
                </div>
                <hr className="border-t border-borderColor" />
              </>
            );
          })
      )}

      {location.pathname != "/contact-list" &&
        CreateGroup.user_id.length > 1 && (
          <div className="absolute bottom-10 flex h-24 w-full items-end bg-gradient-to-t from-primary to-transparent lg:bottom-0">
            <div
              onClick={() => {
                navigate("/create-group");
              }}
              className="primary-gradient mx-auto my-5 w-[90%] cursor-pointer rounded-lg py-2 text-center"
            >
              <TextTranslate text="Next" />
            </div>
          </div>
        )}
    </div>
  );
}
