import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react";
import Button from "../../../components/Button";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import {
  removeSelectedMessage,
  updateMessageOptions,
} from "../../../store/Slices/MessageOptionsSlice";
import useApiPost from "../../../hooks/PostData";
import { updateCurrentConversation } from "../../../store/Slices/CurrentConversationSlice";
import { BlockUserRes, GeneralRes } from "../../../types/ResType";
import { socketInstance } from "../../../socket/socket";
import { ClipLoader } from "react-spinners";
import {
  removeMessageList,
  removeMessagesByIds,
  updateMessagesByIds,
} from "../../../store/Slices/MessageListSlice";
import toast from "react-hot-toast";
import { RxCross2 } from "react-icons/rx";
import { useState } from "react";
import {
  removeChatById,
  updateByChatId,
} from "../../../store/Slices/ChatListSlice";
import { useStarMessageList } from "../../../store/api/useStarMessageList";
import TextTranslate from "../../../utils/TextTranslate";
import { useQueryClient } from "react-query";
import { useConversationMembers } from "../../../store/api/useConversationMembers";
import { updateViewState } from "../../../store/Slices/ViewManagerSlice";

export default function ReusableModal() {
  const dispatch = useAppDispatch();
  const { loading, postData } = useApiPost();
  const [messageDelete, setMessageDelete] = useState<
    "delete_from_everyone" | "delete_for_me" | ""
  >("");
  const MessageOptions = useAppSelector((state) => state.MessageOptions);
  const user_id = useAppSelector((state) => state.userData.user_id);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const selectedGroupMember = useAppSelector(
    (state) => state.SelectedGroupMember,
  );
  const { refetch: refetchConversationMembers } = useConversationMembers();
  const { refetch: refetchStarMessages } = useStarMessageList();
  const queryClient = useQueryClient();

  async function close() {
    // if (MessageOptions.modalName == "delete_chat") {
    //   let message_id_list = MessageOptions.message_list
    //     ?.map((message) => message.message_id)
    //     .join(",")!;

    //   let removeMemberFromGroup = await postData("delete-messages", {
    //     message_id_list,
    //     delete_from_every_one: false,
    //   });
    //   refetch();
    //   toast.success(`${MessageOptions.message_list?.length} messages deleted `);
    // }
    dispatch(updateMessageOptions({ showModal: false }));
    dispatch(
      updateMessageOptions({
        selectMessage: false,
        delete_message: false,
        delete_only_from_me: false,
        message_list: {
          Records: [],
          Pagination: {
            total_pages: 0,
            total_records: 0,
            current_page: 0,
            records_per_page: 0,
          },
        },
      }),
    );
  }

  async function yesDelete({
    delete_from_every_one,
  }: {
    delete_from_every_one?: boolean;
  }) {
    if (MessageOptions.modalName == "block_user") {
      const SelectedConversation = JSON.parse(
        sessionStorage.getItem("selectedConversation")!,
      );
      const blockUserResponse: BlockUserRes = await postData(
        "block/block-unblock",
        {
          user_id: SelectedConversation?.PeerUserData.user_id,
          chat_id: SelectedConversation?.Records[0].chat_id.toString(),
        },
      );
      if (blockUserResponse.status) {
        dispatch(
          updateByChatId({
            chat_id: SelectedConversation?.Records[0].chat_id.toString(),
            last_message: "",
            last_message_type: "",
            blocked_by: blockUserResponse.data.is_blocked
              ? [user_id.toString()]
              : [],
          }),
        );
        if (
          SelectedConversation?.Records[0].chat_id ==
          currentConversationData.chat_id
        ) {
          // sessionStorage.removeItem("currentConversation");
          dispatch(
            updateCurrentConversation({
              is_group_blocked: blockUserResponse.data.is_blocked,
            }),
          );
        }
      } else {
        toast.error("Something went wrong");
      }
      // socketInstance().emit("ChatList", {});
    } else if (MessageOptions.modalName == "clear_chat") {
      // alert(currentConversationData.chat_id)
      await postData("chat/clear-chat", {
        chat_id: currentConversationData.chat_id,
      });
      toast.success("Chat cleared");
      dispatch(
        updateByChatId({
          chat_id: currentConversationData.chat_id,
          last_message: "",
          last_message_type: "text",
          Messages: [],
        }),
      );

      // Remove all pages for a specific chatId from cacheData
      queryClient.invalidateQueries([
        "message_list",
        currentConversationData.chat_id,
      ]);

      let currentConversation = JSON.parse(
        sessionStorage.getItem("currentConversation")!,
      );

      currentConversation.is_message_list_empty = true;

      sessionStorage.setItem(
        "currentConversation",
        JSON.stringify(currentConversation),
      );
      // dispatch(
      //   updateCurrentConversation({
      //     is_message_list_empty: true,
      //   }),
      // );

      dispatch(removeMessageList());
      refetchConversationMembers();
      refetchStarMessages();
    } else if (MessageOptions.modalName == "remove_member") {
      await postData("chat/remove-member", {
        user_id: selectedGroupMember.User.user_id,
        chat_id: currentConversationData.chat_id,
        delete_chat: false,
      });
      refetchConversationMembers();
      toast.success(`${selectedGroupMember.User.full_name} removed from group`);
    } else if (
      MessageOptions.modalName == "exit_from_group" ||
      MessageOptions.modalName == "delete_group"
    ) {
      await postData("chat/remove-member", {
        user_id: user_id,
        chat_id: currentConversationData.chat_id,
        delete_chat: true,
      });
      toast.success(
        `You Exited from group ${currentConversationData.group_name}`,
      );
      // Update group info
      // refetchConversationMembers();
      // Update chatlist
      dispatch(removeChatById(currentConversationData.chat_id));
      // socketInstance().emit("ChatList", {});
      // Update messagelist
      dispatch(removeMessageList());
      dispatch(
        updateViewState({
          show_chats_sidebar: false,
        }),
      );
      // sessionStorage.removeItem("currentConversation");
      dispatch(updateCurrentConversation({ chat_id: -1, user_id: 0 }));
    } else if (MessageOptions.modalName == "delete_chat") {
      // let message_id_list = MessageOptions.message_list
      //   ?.map((message) => message.message_id)
      //   .join(",")!;
      const message_id_list = MessageOptions.message_list.Records.map(
        (message) => message.message_id,
      );
      // await postData("delete-messages", {
      //   message_id_list,
      //   delete_from_every_one: String(delete_from_every_one),
      //   chat_id: currentConversationData.chat_id,
      // });
      message_id_list.map((message_id) => {
        socketInstance().emit(
          delete_from_every_one ? "delete_for_everyone" : "delete_for_me",
          {
            chat_id: currentConversationData.chat_id,
            message_id,
          },
        );
      });

      // Refetch the conversation details to update the media,links and document in sidebar =====================================
      refetchConversationMembers();
      // Refetch the star message ==================================================================================
      refetchStarMessages();
      // Update chatlist
      // socketInstance().emit("ChatList", {});
      toast.success(
        `${MessageOptions.message_list.Records.length} messages deleted `,
      );

      if (delete_from_every_one) {
        message_id_list.map((message_id) => {
          dispatch(
            updateMessagesByIds({
              message: delete_from_every_one
                ? // ? "🚫 This message was deleted!"
                  "🚫 You deleted this message!"
                : "🚫 You deleted this message!",
              message_id: message_id,
              delete_from_everyone: true,
              user_id: "",
            }),
          );
        });
      } else {
        dispatch(removeMessagesByIds(message_id_list));
      }

      // Clear selected message on close
      dispatch(removeSelectedMessage());
      dispatch(
        updateMessageOptions({
          message_list: {
            Records: [],
            Pagination: {
              total_pages: 0,
              total_records: 0,
              current_page: 0,
              records_per_page: 0,
            },
          },
          delete_from_every_one: false,
          delete_message: false,
          selectMessage: false,
        }),
      );
    } else if (MessageOptions.modalName == "delete_conversation") {
      const SelectedConversation = JSON.parse(
        sessionStorage.getItem("selectedConversation")!,
      );
      const deleteChatResponse: GeneralRes = await postData("chat/clear-chat", {
        chat_id: SelectedConversation?.Records[0].chat_id,
        delete_chat: true,
      });

      if (deleteChatResponse.status) {
        queryClient.invalidateQueries([
          "message_list",
          SelectedConversation?.Records[0].chat_id,
        ]);

        // if deleted conversation is current coversation than remove the message list =======================================
        if (
          currentConversationData.chat_id ==
          SelectedConversation?.Records[0].chat_id
        ) {
          // sessionStorage.removeItem("currentConversation");
          dispatch(removeMessageList());
          // Remove all pages for a specific chatId from cacheData
          dispatch(
            updateCurrentConversation({
              chat_id: -1,
              group_name: "",
              group_icon: "",
              profile_pic: "",
              user_id: 0,
              is_group_blocked: false,
              chat_type: "private",
              is_message_list_empty: true,
            }),
          );
        }
        if (SelectedConversation?.Records[0].chat_id) {
          dispatch(removeChatById(SelectedConversation?.Records[0].chat_id));
        }
        toast.success("Conversation Deleted!", { position: "bottom-left" });
      } else {
        toast.error("Something went wrong!", { position: "bottom-left" });
      }
    }
    dispatch(updateMessageOptions({ showModal: false }));
  }

  return (
    <>
      <Dialog
        open={MessageOptions.showModal}
        as="div"
        className="relative z-10"
        onClose={() => {
          // close();
        }}
      >
        <div className="fixed inset-0 z-50 bg-black bg-opacity-50 backdrop-blur-sm">
          <div className="flex min-h-full items-center justify-center p-4">
            <DialogPanel
              transition
              className="data-[closed]:transform-[scale(95%)] w-full max-w-lg rounded-xl bg-modalBg p-6 shadow-[rgba(17,_17,_26,_0.3)_0px_0px_16px] backdrop-blur-md duration-300 ease-in-out data-[closed]:opacity-0"
            >
              <div
                onClick={() => {
                  close();
                }}
                className="absolute -right-3 -top-3 grid h-10 w-10 cursor-pointer place-content-center rounded-full bg-modalBg shadow-2xl"
              >
                <RxCross2 className="text-3xl" />
              </div>
              <DialogTitle as="h3" className="text-xl font-medium">
                {MessageOptions.title}
              </DialogTitle>
              <p className="mt-2 text-sm opacity-70">
                {MessageOptions.description}
              </p>
              <div
                className={`mb-2 ml-auto mr-0 mt-10 flex ${MessageOptions.modalName == "delete_chat" || MessageOptions.modalName == "exit_from_group" ? "w-[100%]" : "w-[70%]"} gap-3`}
              >
                <button
                  onClick={() => {
                    if (MessageOptions.delete_message) {
                      // dispatch(
                      //   updateMessageOptions({ delete_from_every_one: false }),
                      // );
                      yesDelete({ delete_from_every_one: false });
                      setMessageDelete("delete_for_me");
                    } else {
                      close();
                    }
                  }}
                  className={`relative h-11 ${MessageOptions.delete_only_from_me ? "" : "w-full"} ml-auto mr-0 min-w-fit overflow-hidden text-nowrap rounded-lg border border-primaryColor !bg-transparent px-4 py-2 text-base outline-none lg:px-9 lg:text-lg`}
                >
                  <div className="">
                    {MessageOptions.modalName == "delete_chat" ? (
                      loading && messageDelete == "delete_for_me" ? (
                        <ClipLoader size={25} />
                      ) : (
                        <TextTranslate text="Delete for me" />
                      )
                    ) : (
                      <TextTranslate text="Cancel" />
                    )}
                  </div>
                </button>

                {!MessageOptions.delete_only_from_me && (
                  <Button
                    onClickFunc={() => {
                      if (MessageOptions.delete_message) {
                        dispatch(
                          updateMessageOptions({ delete_from_every_one: true }),
                        );
                      }
                      yesDelete({ delete_from_every_one: true });
                      setMessageDelete("delete_from_everyone");
                    }}
                    className={`!h-11 min-w-fit ${(MessageOptions.delete_only_from_me, "MessageOptions.delete_only_from_me")} `}
                    text={
                      <TextTranslate
                        text={
                          loading && messageDelete == "delete_from_everyone" ? (
                            <ClipLoader size={25} />
                          ) : MessageOptions.modalName == "clear_chat" ? (
                            "Clear"
                          ) : MessageOptions.modalName == "delete_chat" ? (
                            "Delete for everyone"
                          ) : MessageOptions.modalName == "report_user" ? (
                            "Report"
                          ) : MessageOptions.modalName == "remove_member" ? (
                            "Remove"
                          ) : MessageOptions.modalName == "delete_group" ? (
                            "Delete Group"
                          ) : MessageOptions.modalName == "exit_from_group" ? (
                            "Exit From Group"
                          ) : MessageOptions.modalName == "block_user" ? (
                            currentConversationData.is_group_blocked ? (
                              "Unblock"
                            ) : (
                              "Block"
                            )
                          ) : MessageOptions.modalName ==
                            "delete_conversation" ? (
                            "Delete"
                          ) : (
                            ""
                          )
                        }
                      />
                    }
                  />
                )}
              </div>
            </DialogPanel>
          </div>
        </div>
      </Dialog>
    </>
  );
}
