import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/react";
import { ContextMenuTrigger } from "rctx-contextmenu";
import { updateMessageOptions } from "../../../store/Slices/MessageOptionsSlice";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { updateCreateGroupData } from "../../../store/Slices/CreateGroupSlice";
import { TbUserPlus } from "react-icons/tb";
import { updateSelectedGroupMember } from "../../../store/Slices/SelectedGroupMemberSlice";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { PiDotsThreeVerticalBold } from "react-icons/pi";
import useApiPost from "../../../hooks/PostData";
import toast from "react-hot-toast";
import TextTranslate from "../../../utils/TextTranslate";
import { useConversationMembers } from "../../../store/api/useConversationMembers";
import { GroupMemberRecord } from "../../../types/ResType";
import ShowSavedName from "../../../components/ShowSavedName";
import { ClipLoader } from "react-spinners";
import { useTheme } from "../../../context/ThemeProvider";
import { useNavigateToChat } from "../../../hooks/useNavigateToChat";

export default function GroupMembers() {
  const {
    data: GroupMemberData,
    isLoading: GroupMemberDataLoading,
    refetch,
  } = useConversationMembers();
  const OnlineUserList = useAppSelector((state) => state.OnlineUserList);
  const userData = useAppSelector((state) => state.userData);
  const dispatch = useAppDispatch();
  const { postData } = useApiPost();
  // @ts-ignore
  const { theme } = useTheme();
  const selectedGroupMember = useAppSelector(
    (state) => state.SelectedGroupMember,
  );
  const navigateToChat = useNavigateToChat();
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const ChatListArray = useAppSelector((state) => state.chatList);

  async function makeGrouAdmin() {
    const createGroupAdminRes = await postData("chat/create-group-admin", {
      admin_user_id: selectedGroupMember.user_id,
      chat_id: currentConversationData.chat_id.toString(),
    });
    refetch();
    toast.success(
      `${selectedGroupMember.User.full_name} ${selectedGroupMember.is_admin ? "removed from" : "is now"} group admin`,
    );
  }

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

    navigateToChat({
      chat_id: chatData?.chat_id ?? -1,
      chat_type: "private",
      full_name: member.User.full_name,
      group_name: "",
      group_icon: "",
      profile_pic: member.User.profile_pic,
      user_id: member.User.user_id,
      user_name: member.User.user_name,
      email_id: member.User.email,
      unseen_count: 0,
      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 (
    <>
      {currentConversationData.chat_type == "group" && (
        <div className="items-center space-y-3 border border-borderColor px-8 py-4">
          <div className="flex justify-between">
            <div className="text-sm text-darkText">
              <TextTranslate text="Group Members" />
            </div>
            <div className="pr-3 text-sm text-darkText">
              {GroupMemberData?.data.Records.length}
            </div>
          </div>

          {GroupMemberData?.data.Records.find(
            (convoUser) => convoUser.User.user_id === userData.user_id,
          )?.is_admin && (
              <div
                onClick={() => {
                  const existing_member_user_id =
                    GroupMemberData?.data.Records.map(
                      (user) => user.User.user_id,
                    );
                  dispatch(
                    updateCreateGroupData({
                      show_add_member_modal: true,
                      existing_member_user_id: existing_member_user_id,
                    }),
                  );
                }}
                className={`flex cursor-pointer items-center py-2`}
              >
                <div className="relative mr-3 grid h-10 w-10 place-content-center rounded-full primary-gradient 2xl:h-12 2xl:w-12">
                  <TbUserPlus className="h-5 w-5 object-cover 2xl:h-7 2xl:w-7" />
                </div>

                <div className="text-base font-medium capitalize text-darkText">
                  <TextTranslate text="Add Member" />
                </div>
              </div>
            )}

          {GroupMemberDataLoading ? (
            <div className="flex h-60 items-center justify-center">
              <ClipLoader
                size={19}
                color={theme == "dark" ? "white" : "black"}
              />
            </div>
          ) : (
            GroupMemberData?.data.Records.map((member) => {
              return (
                <>
                  <ContextMenuTrigger id="my-context-menu-2">
                    <div
                      onContextMenu={() => {
                        dispatch(updateSelectedGroupMember(member));
                      }}
                      className="relative flex"
                    >
                      <div className="relative mr-3">
                        <LoadingSkeletonImageDynamic
                          radius=""
                          className="min-h-10 min-w-10 rounded-full object-cover 2xl:min-h-12 2xl:min-w-12"
                          image_height="100%"
                          image_url={member.User.profile_pic}
                          image_width="100%"
                        />
                        {OnlineUserList.onlineUsers.find(
                          (user) => user.user_id == member.User.user_id,
                        ) && (
                            <img
                              onClick={() => {
                                changeCurrentConversation(member);
                              }}
                              className="absolute bottom-0 right-0 z-30 h-4 w-4"
                              src="/Home/Online_Green_dot.png"
                              alt=""
                            />
                          )}
                      </div>
                      <div
                        onClick={() => {
                          changeCurrentConversation(member);
                        }}
                        className="w-full cursor-pointer"
                      >
                        <div className="text-sm font-medium capitalize text-darkText">
                          {member.User.user_id == userData.user_id ? (
                            "You"
                          ) : (
                            <ShowSavedName
                              user_id={member.User.user_id.toString()}
                              name={member.User.full_name}
                            />
                          )}
                        </div>
                        <div className="flex justify-between">
                          <div className="font-SourceSansPro line-clamp-1 items-center gap-x-1 text-sm text-[#959595]">
                            {member.User.user_name || "Available"}
                          </div>
                          {member.is_admin && (
                            <div
                              className="font-SourceSansPro line-clamp-1 items-center gap-x-1 rounded-lg px-3 py-1 text-xs"
                              style={{
                                backgroundColor: 'color-mix(in srgb, var(--theme-color) 15%, transparent)',
                                color: 'var(--theme-text-color)',
                              }}
                            > 
                              <TextTranslate text="Group Admin" />
                            </div>

                          )}
                        </div>
                      </div>

                      {GroupMemberData?.data.Records.find(
                        (convoUser) =>
                          convoUser.User.user_id === userData.user_id,
                      )?.is_admin && member.User.user_id != userData.user_id && (
                          <Menu>
                            <MenuButton className="inline-flex items-center gap-2 rounded-md px-1 py-1.5 text-sm/6 font-semibold shadow-2xl focus:outline-none">
                              <PiDotsThreeVerticalBold
                                onClick={() => {
                                  dispatch(updateSelectedGroupMember(member));
                                }}
                                className="cursor-pointer text-2xl"
                              />
                            </MenuButton>

                            <MenuItems className="absolute bottom-0 right-6 w-52 rounded-xl border border-borderColor bg-modalBg p-1 text-sm transition duration-200 ease-out focus:outline-none">
                              <MenuItem>
                                {({ focus }) => (
                                  <button
                                    onClick={() => makeGrouAdmin()}
                                    className={`group flex w-full items-center gap-2 rounded-lg py-1.5 pl-6 ${focus ? "bg-dropdownOptionHover" : ""
                                      }`}
                                  >
                                    {member.is_admin
                                      ? "Remove From Admin"
                                      : "Make Group Admin"}
                                  </button>
                                )}
                              </MenuItem>
                              <MenuItem>
                                {({ focus }) => (
                                  <button
                                    onClick={() =>
                                      dispatch(
                                        updateMessageOptions({
                                          showModal: true,
                                          title: `Are you sure you want Remove ${selectedGroupMember.User.full_name} From this Group??`,
                                          description: "",
                                          modalName: "remove_member",
                                        }),
                                      )
                                    }
                                    className={`group flex w-full items-center gap-2 rounded-lg py-1.5 pl-6 ${focus ? "bg-dropdownOptionHover" : ""
                                      }`}
                                  >
                                    Remove
                                  </button>
                                )}
                              </MenuItem>
                            </MenuItems>
                          </Menu>
                        )}
                    </div>
                  </ContextMenuTrigger>
                </>
              );
            })
          )}
        </div>
      )}
    </>
  );
}
