/* eslint-disable @typescript-eslint/ban-ts-comment */
import { IoSearchOutline } from "react-icons/io5";
import { updateViewState } from "../../../store/Slices/ViewManagerSlice";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { RxCross1 } from "react-icons/rx";
import { useTheme } from "../../../context/ThemeProvider";
import LinkPreview from "../../../components/LinkPreview";
import { useEffect, useRef, useState } from "react";
import { updateSearchMessageResult } from "../../../store/Slices/SearchMessageSlice";
import { ClipLoader } from "react-spinners";
import { updateNavigateToSpesificMessage } from "../../../store/Slices/NavigateToSpesificMessageSlice";
import { useTranslateText } from "../../../hooks/useTranslateText";
import { useSearchMessages } from "../../../store/api/useSearchMessages";
import { searchMessageRecord } from "../../../types/ResType";
import ShowSavedName from "../../../components/ShowSavedName";
import chatSidebarTime from "../../../utils/chatSidebarTime";
import SearchNotFoundAnimation from "../../../components/SearchNotFoundAnimation";

export default function SearchMessage() {
  const dispatch = useAppDispatch();
  const userData = useAppSelector((state) => state.userData);
  const [searchText, setSearchText] = useState("");
  const viewImageSlice = useAppSelector((state) => state.ViewManager);
  const translate = useTranslateText();
  const { data: SearchMessageData, isLoading } = useSearchMessages(searchText);
  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (viewImageSlice?.showSearchMessage == false) {
      setSearchText("");
    }
  }, [viewImageSlice?.showSearchMessage]);

  useEffect(() => {
    if (viewImageSlice?.showSearchMessage === true) {
      // Focus the input when the sidebar opens
      setTimeout(() => {
        searchInputRef.current?.focus();
      }, 100); // Slight delay to ensure DOM is ready
    } else {
      setSearchText(""); // Clear text when sidebar closes
    }
  }, [viewImageSlice?.showSearchMessage]);

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

  function navigateToThatChat(SearchResult: searchMessageRecord) {
    dispatch(
      updateNavigateToSpesificMessage({
        chat_id: SearchResult.chat_id,
        navigate_to_message: true,
        message_id: SearchResult.message_id,
      }),
    );
  }

  return (
    <div>
      <div className="flex items-center gap-3 bg-otherProfileSidebar px-4 pt-6 lg:py-8">
        <RxCross1
          className="ml-2 cursor-pointer text-xl"
          onClick={() => {
            dispatch(updateViewState({ showSearchMessage: false }));
            dispatch(updateSearchMessageResult([]));
          }}
        />
        <span className="">{translate("Search Messages")}</span>
      </div>
      <div className="my-5 flex flex-col gap-y-4">
        <div className="relative mx-4 mt-4 h-fit">
          <IoSearchOutline className="absolute left-3 top-2 text-2xl text-lightText" />
          <input
            ref={searchInputRef}
            value={searchText}
            onChange={(e) => {
              setSearchText(e.target.value);
              if (e.target.value == "") {
                dispatch(updateSearchMessageResult([]));
                return;
              }
            }}
            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 Messages")}
          />
          {isLoading && (
            <ClipLoader
              className="absolute right-3 top-2"
              color={theme == "dark" ? "white" : "black"}
              size={22}
            />
          )}
        </div>

        {/* Search Results ====================================================================================*/}
        {SearchMessageData?.data?.Records?.filter(
          (message) =>
            message.deleted_for_everyone == false && // Exclude messages deleted for everyone
            !message.deleted_for.includes(userData.user_id.toString()), // Exclude messages deleted for the current user
        ).length == 0 ? (
          <div className="grid h-96 place-content-center gap-5">
            <SearchNotFoundAnimation />
            <div>{translate("No Such Message Found")}</div>
          </div>
        ) : (
          // <div className="my-6 text-center text-sm text-lightText">
          //   Search for messages of{" "}
          //   {currentConversationData.is_group
          //     ? currentConversationData.group_name
          //     : currentConversationData.user_name}
          // </div>
          <div className="space-y-4">
            {SearchMessageData?.data?.Records?.filter(
              (message) =>
                message.deleted_for_everyone == false && // Exclude messages deleted for everyone
                !message.deleted_for.includes(userData.user_id.toString()), // Exclude messages deleted for the current user
            ).map((message) => {
              return (
                <>
                  <div
                    onClick={() => {
                      navigateToThatChat(message);
                    }}
                    className={`my-2 cursor-pointer  hover:bg-primary px-5`}
                  >
                    <div className={`flex w-full items-center text-sm`}>
                      <div className="flex items-start gap-1">
                        {message.User.user_id == userData.user_id ? (
                          "You"
                        ) : (
                          <ShowSavedName
                            user_id={message.User.user_id.toString()}
                            name={message.User.full_name}
                          />
                        )}
                        {" : "}
                      </div>

                      <div
                        className={`relative inline-block h-fit min-w-[1rem] max-w-[17rem] rounded-lg py-1 pl-2 sm:max-w-xl 2xl:max-w-3xl`}
                      >
                        {message.message_content}
                      </div>
                    </div>
                    {/* Date */}
                    <div className="text-sm text-lightText">
                      {chatSidebarTime(message.createdAt)}
                    </div>
                  </div>
                </>
                // Old design (better design)
                // <>
                //   <div
                //     onClick={() => {
                //       navigateToThatChat(message);
                //     }}
                //     className={`my-2 flex cursor-pointer flex-col rounded-lg`}
                //   >
                //     <div className="flex items-end justify-end">
                //       <div
                //         className={`cursor-pointer" : "" mx-2 flex w-full flex-col space-y-2 ${message.sender_id == userData.user_id ? "order-1 items-end" : "order-2"}`}
                //       >
                //         <div className="flex items-start gap-1">
                //           <div
                //             className={`${
                //               message.sender_id == userData.user_id
                //                 ? "primary-gradient order-1 rounded-br-none"
                //                 : "order-2 rounded-bl-none bg-otherMessageBg"
                //             } relative inline-block h-fit min-w-[1rem] max-w-[17rem] rounded-lg px-2 py-1 text-sm sm:max-w-xl 2xl:max-w-3xl`}
                //           >
                //             {message.message_type === "text" ? (
                //               message.message_content
                //             ) : message.message_type === "link" ? (
                //               <LinkPreview
                //                 right={message.sender_id == userData.user_id}
                //                 url={message.message_content}
                //               />
                //             ) : (
                //               message.message_content
                //             )}
                //           </div>
                //           <img
                //             src={message.User.profile_pic}
                //             alt="My profile"
                //             className={`h-7 w-7 rounded-full object-cover ${
                //               message.sender_id == userData.user_id
                //                 ? "order-2"
                //                 : "order-1"
                //             } mt-auto ${
                //               ["video", "image"].includes(message.message_type!)
                //                 ? "mb-7"
                //                 : "mb-5"
                //             }`}
                //           />
                //         </div>
                //       </div>
                //     </div>
                //   </div>
                // </>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
