/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import React, { useEffect, useRef, useState } from "react";
import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react";
import { RxCross2 } from "react-icons/rx";
import { IoSearchOutline } from "react-icons/io5";
import { useTheme } from "../../../../context/ThemeProvider";
import ForwardMessageConversationsList from "./ForwardMessageConversationsList";
import { useAppDispatch, useAppSelector } from "../../../../utils/hooks";
import { updateMessageOptions } from "../../../../store/Slices/MessageOptionsSlice";
import { clearnForwardedList } from "../../../../store/Slices/ForwardMessageSlice";
import { useTranslateText } from "../../../../hooks/useTranslateText";
import ForwardMessageToContactList from "./ForwardMessageToContactList";
import useApiPost from "../../../../hooks/PostData";
import { ClipLoader } from "react-spinners";

const ForwardMessageModal: React.FC = () => {
  const MessageOptions = useAppSelector((state) => state.MessageOptions);
  const dispatch = useAppDispatch();
  const [searchUser, setsearchUser] = useState("");
  const [tab, setTab] = useState<"recent_chats" | "contacts">("recent_chats");
  const searchUserRef = useRef<HTMLInputElement>(null);
  const ForwardMessageData = useAppSelector((state) => state.ForwardMessage);

  // @ts-ignore
  const { theme } = useTheme();

  const { loading, postData } = useApiPost();

  async function forwardMessageApiCall({
    chat_id,
    user_id,
  }: {
    chat_id?: number;
    user_id?: number;
  }) {
    if (!MessageOptions.message_list?.Records) return;
    // @ts-ignore
    for (const e of MessageOptions.message_list?.Records) {
      await postData("chat/forward-message", {
        from_chat_id: e.chat_id,
        to_chat_id: chat_id,
        message_id: e.message_id,
        user_id: user_id,
      });
    }
  }

  async function forwardMessage() {
    ForwardMessageData.forwarded_conversations_id.forEach(async (e) => {
      await forwardMessageApiCall({ chat_id: e, user_id: undefined });
    });
    ForwardMessageData.forwarded_user_id.forEach(async (e) => {
      await forwardMessageApiCall({ chat_id: undefined, user_id: e });
    });
    handleCloseModal();
  }

  const translate = useTranslateText();
  const handleCloseModal = () => {
    dispatch(clearnForwardedList());
    dispatch(
      updateMessageOptions({
        show_forward_message_modal: false,
        selectMessage: false,
        forward_message: false,
        message_list: {
          Records: [],
          Pagination: {
            total_pages: 0,
            total_records: 0,
            current_page: 0,
            records_per_page: 0,
          },
        },
        delete_from_every_one: false,
      }),
    );
  };

  useEffect(() => {
    if (searchUserRef.current && MessageOptions.show_forward_message_modal) {
      searchUserRef.current.focus();
    }
  }, [MessageOptions.show_forward_message_modal]);

  return (
    <Dialog
      open={MessageOptions.show_forward_message_modal}
      onClose={() => {}}
      className="relative z-50"
    >
      <div className="fixed inset-0 bg-black/35 backdrop-blur-sm">
        <div className="flex min-h-full items-center justify-center p-4">
          <DialogPanel className="relative max-h-[85vh] w-full max-w-md overflow-hidden rounded-xl bg-primary transition-transform duration-300 ease-out">
            <DialogTitle
              as="h3"
              style={{
                backgroundSize: "100%",
              }}
              className="w-full space-y-5 primary-gradient bg-no-repeat px-4 xl:space-y-7"
            >
              <div className="flex items-center gap-3 py-10 font-semibold text-black">
                <RxCross2
                  onClick={handleCloseModal}
                  className="cursor-pointer text-2xl"
                />
                <span className="">Forward To</span>
              </div>
            </DialogTitle>
            <div className="relative mx-4 mt-4 h-fit">
              <IoSearchOutline className="absolute left-3 top-2 text-2xl text-lightText" />
              <input
                ref={searchUserRef}
                value={searchUser}
                onChange={(e) => {
                  setsearchUser(e.target.value);
                }}
                className={` ${
                  theme == "dark" ? "bg-transparent" : "bg-[#F2F2F2]"
                } w-full rounded-xl border border-borderColor py-2 pl-11 placeholder-lightText outline-none`}
                type="text"
                placeholder={translate("Search User")}
              />
            </div>
            {/* Tabs */}
            <div className="grid grid-cols-2 overflow-hidden rounded-xl border border-borderColor mx-5 mb-3 mt-4 text-center">
              <div
                className={`cursor-pointer px-4 py-2 ${tab == "recent_chats" ? "bg-secondary" : ""}`}
                onClick={() => {
                  setTab("recent_chats");
                }}
              >
                Recent Chats
              </div>
              <div
                className={`cursor-pointer px-4 py-2 ${tab == "contacts" ? "bg-secondary" : ""}`}
                onClick={() => {
                  setTab("contacts");
                }}
              >
                Contacts
              </div>
            </div>
            {tab == "recent_chats" ? (
              <ForwardMessageConversationsList
                searchUser={searchUser}
                handleCloseModal={handleCloseModal}
              />
            ) : (
              <ForwardMessageToContactList
                searchUser={searchUser}
                handleCloseModal={handleCloseModal}
              />
            )}
            {ForwardMessageData.forwarded_conversations_id.length == 0 &&
            ForwardMessageData.forwarded_user_id.length == 0 ? (
              ""
            ) : (
              <div className="absolute bottom-0 flex h-24 w-full items-end bg-gradient-to-t from-primary to-transparent">
                <div
                  onClick={() => {
                    forwardMessage();
                    // navigate("/create-group");
                  }}
                  className="primary-gradient mx-auto my-5 w-[90%] cursor-pointer rounded-lg py-2 text-center"
                >
                  {loading ? (
                    <ClipLoader
                      size={19}
                      color={theme == "dark" ? "white" : "black"}
                    />
                  ) : (
                    "Forward"
                  )}
                </div>
              </div>
            )}
          </DialogPanel>
        </div>
      </div>
    </Dialog>
  );
};

export default ForwardMessageModal;
