/* eslint-disable @typescript-eslint/ban-ts-comment */
import { useStarMessageList } from "../../../store/api/useStarMessageList";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import LinkPreview from "../../../components/LinkPreview";
// @ts-ignore
import { AudioPlayer } from "react-audio-player-component";
import LoadingSkeletonImageDynamic from "../../../components/LoadingSkeletonImageDynamic";
import { FaPlay } from "react-icons/fa6";
import { useTheme } from "../../../context/ThemeProvider";
import CallInMessageList from "../MessageList/CallInMessageList";
import GoogleMapReact from "google-map-react";
import { formatTimeOnly } from "../../../utils/formatUTCtoLocalDate";
import { MdArrowLeft, MdArrowRight, MdLocationPin } from "react-icons/md";
import { ClipLoader } from "react-spinners";
import {
  setViewImage,
  updateViewState,
} from "../../../store/Slices/ViewManagerSlice";
import { updateCurrentConversation } from "../../../store/Slices/CurrentConversationSlice";
import { removeMessageList } from "../../../store/Slices/MessageListSlice";
import { updateSearchMessageResult } from "../../../store/Slices/SearchMessageSlice";
import { socketInstance } from "../../../socket/socket";
import { updateMessageOptions } from "../../../store/Slices/MessageOptionsSlice";

import { updateNavigateToSpesificMessage } from "../../../store/Slices/NavigateToSpesificMessageSlice";
import { useEffect } from "react";
import TextTranslate from "../../../utils/TextTranslate";
import { Message } from "../../../types/StarMessageListTypes";
import SearchNotFoundAnimation from "../../../components/SearchNotFoundAnimation";

export default function StarMessageList() {
  const { data, isLoading } = useStarMessageList();
  const userData = useAppSelector((state) => state.userData);
  const dispatch = useAppDispatch();
  const CurrentConversation = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const ChatListArray = useAppSelector((state) => state.chatList);
  const ContactList = useAppSelector((state) => state.ContactList);
  // @ts-ignore
  const { theme } = useTheme();

  const handleImageClick = (imageIndex: number) => {
    dispatch(
      setViewImage({
        show_image: true,
        image_src: image_urls,
        currentIndex: imageIndex,
      }),
    );
  };

  function returnSavedName({
    name,
    user_id,
  }: {
    name: string;
    user_id: number;
  }) {
    if (user_id == userData.user_id) {
      return "You";
    }
    const user = ContactList?.data?.find((e) => e?.user_id == user_id);
    return user?.name ?? name;
  }

  const urls = data?.data?.Records?.filter((message) => {
    return (
      (message.message_type === "image" ||
        message.message_type === "gif" ||
        message.message_type === "video") &&
      message.message_type
    );
  });

  const image_urls = urls?.map((message) =>
    message.message_content.replace(/\\/g, "/"),
  );

  function navigateToThatChat(starMessage: Message) {
    if (CurrentConversation.chat_id != starMessage.chat_id) {
      const conversationData = ChatListArray.Chats.find(
        (chatUser) =>
          chatUser.Records[0].chat_id == starMessage.chat_id &&
          chatUser.Records[0].chat_type == "private",
      );

      dispatch(
        updateCurrentConversation({
          chat_id: conversationData?.Records[0].chat_id,
          createdAt: conversationData?.Records[0].createdAt,
          group_name: conversationData?.Records[0].group_name,
          group_icon: conversationData?.Records[0].group_icon,
          chat_type: conversationData?.Records[0].chat_type,
          profile_pic: conversationData?.PeerUserData.profile_pic,
          updatedAt: conversationData?.Records[0].updatedAt,
          user_id: conversationData?.PeerUserData.user_id,
          user_name: conversationData?.PeerUserData.user_name,
          email_id: conversationData?.PeerUserData.email,
          full_name: conversationData?.PeerUserData.full_name,
        }),
      );
      dispatch(removeMessageList());
      dispatch(updateSearchMessageResult([]));
      dispatch(updateViewState({ showSearchMessage: false }));
      const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

      // socketInstance().emit("message_list", {
      //   chat_id: starMessage.chat_id,
      //   user_timezone: timeZone,
      //   pinned: true,
      //   // message_id: starMessage.message_id! + 5,
      // });
      dispatch(
        updateMessageOptions({
          isMessageLoading: true,
        }),
      );
    }

    dispatch(
      updateNavigateToSpesificMessage({
        chat_id: starMessage.chat_id,
        navigate_to_message: true,
        message_id: starMessage.message_id,
      }),
    );
  }
  useEffect(() => {
    console.log(data, "star message data +++++++++++++++++");
  }, [data]);

  return (
    <div className="flex h-full max-h-[88vh] flex-col gap-y-2 overflow-y-auto px-4 pb-40 py-5">
      {isLoading ? (
        <div className="grid h-96 place-content-center">
          <ClipLoader
            className=""
            color={theme == "dark" ? "white" : "black"}
            size={22}
          />
        </div>
      ) : (
        <>
          {data?.data?.Records?.length == 0 ||
            data?.data?.Records?.length == undefined ? (
            <div className="grid h-96 place-content-center gap-5">
              <SearchNotFoundAnimation />
              <div>
                <TextTranslate text="No Star Message Found" />
              </div>
            </div>
          ) : (
            // Filter out the delted messages
            data?.data?.Records.filter(
              (starMessage) =>
                starMessage.deleted_for_everyone == false && // Exclude messages deleted for everyone
                !starMessage.deleted_for.includes(userData.user_id.toString()), // Exclude messages deleted for the current user
            ).map((starMessage) => {
              const imageIndex = image_urls?.indexOf(
                starMessage.message_content.replace(/\\/g, "/"),
              );

              return (
                <>
                  <div className={`my-2 flex flex-col rounded-lg`}>
                    <div className="flex items-end justify-end">
                      <div
                        onClick={() => {
                          navigateToThatChat(starMessage);
                        }}
                        className={`mx-2 flex w-full cursor-pointer flex-col justify-center space-y-2`}
                      >
                        <div>
                          <div
                            onClick={() => {
                              // navigateToThatChat(starMessage);
                            }}
                            className={`flex cursor-pointer items-center gap-2`}
                          >
                            <img
                              src={starMessage.User?.profile_pic}
                              alt="My profile"
                              className={`mb-2 h-7 w-7 rounded-full object-cover`}
                            />
                            {/* Sender */}
                            <div className={``}>
                              {starMessage.User.user_id == userData.user_id
                                ? "You"
                                : `${starMessage.Chat.chat_type == "group"
                                  ? starMessage.Chat.group_name
                                  : returnSavedName({
                                    name: starMessage.peer_user.full_name,
                                    user_id:
                                      starMessage.peer_user.user_id,
                                  })
                                }`}
                            </div>

                            {/* {starMessage.sender_id == userData.user_id ? (
                              <MdArrowLeft className="text-xl" />
                            ) : ( */}
                            <MdArrowRight className="text-xl" />
                            {/* // )} */}
                            {/* Receiver */}
                            <div className={``}>
                              {/* This means if current user is not sender then he/she is receiver ==========================*/}
                              {starMessage?.sender_id !== userData.user_id
                                ? "You"
                                : `${starMessage.Chat.chat_type == "group"
                                  ? starMessage.Chat.group_name
                                  : returnSavedName({
                                    name: starMessage.peer_user.full_name,
                                    user_id:
                                      starMessage.peer_user.user_id,
                                  })
                                }`}
                            </div>
                          </div>
                          <div
                            className={`${!["text", "audio"].includes(
                              starMessage.message_type!,
                            )
                              ? ""
                              : starMessage.sender_id == userData.user_id
                                ? "primary-gradient rounded-bl-none"
                                : "rounded-bl-none bg-otherMessageBg"
                              } ${starMessage.message_type == "text" && "px-2"} group relative flex w-fit min-w-[1rem] max-w-[90%] rounded-lg py-1 text-sm`}
                          >
                            {starMessage.message_type === "text" ? (
                              <div>{starMessage.message_content}</div>
                            ) : starMessage.message_type === "link" ? (
                              <div
                                className={`w-[90%] ${starMessage.sender_id == userData.user_id
                                  ? "ml-auto"
                                  : "rounded-bl-none bg-otherMessageBg"
                                  } `}
                              >
                                <LinkPreview
                                  right={
                                    starMessage.sender_id == userData.user_id
                                  }
                                  url={starMessage.message_content}
                                />
                              </div>
                            ) : starMessage.message_type === "image" ? (
                              <div
                              // onClick={() => {
                              //   handleImageClick(imageIndex!);
                              // }}
                              >
                                <LoadingSkeletonImageDynamic
                                  radius=""
                                  className={` ${starMessage.sender_id == userData.user_id
                                    ? "rounded-br-none"
                                    : "rounded-bl-none"
                                    } h-32 w-56 cursor-pointer select-none rounded-lg object-cover transition-all duration-300 lg:h-36 lg:w-60`}
                                  image_height=""
                                  image_url={starMessage.message_content}
                                  image_width=""
                                />
                              </div>
                            ) : starMessage.message_type === "gif" ? (
                              <div
                              // onClick={() => {
                              //   handleImageClick(imageIndex!);
                              // }}
                              >
                                <LoadingSkeletonImageDynamic
                                  radius=""
                                  className={` ${starMessage.sender_id == userData.user_id
                                    ? "rounded-bl-none"
                                    : "rounded-bl-none"
                                    } h-32 w-56 cursor-pointer select-none rounded-lg object-cover transition-all duration-300 lg:h-36 lg:w-60`}
                                  image_height=""
                                  image_url={starMessage.message_content}
                                  image_width=""
                                />
                              </div>
                            ) : starMessage.message_type === "video" ? (
                              <div
                                // onClick={() => {
                                //   handleImageClick(imageIndex!);
                                // }}
                                className={`relative h-36 w-60 cursor-pointer overflow-hidden rounded-lg`}
                              >
                                <div className="absolute grid h-full w-full place-content-center">
                                  <FaPlay className="h-11 w-11 rounded-full bg-[#0000008F] p-3 text-white" />
                                </div>
                                <LoadingSkeletonImageDynamic
                                  radius=""
                                  className={`h-36 w-60 select-none object-cover`}
                                  image_height="100%"
                                  image_url={starMessage.message_thumbnail}
                                  image_width="100%"
                                />
                              </div>
                            ) : starMessage.message_type === "doc" ? (
                              <div
                                className={`w-full max-w-72 rounded-[9px] ${starMessage.sender_id == userData.user_id ? "primary-gradient rounded-bl-none" : "rounded-bl-none bg-pdfBg"} min-w-72 px-1 pb-3 pt-1`}
                              >
                                <a
                                  // href={starMessage.message_content}
                                  target="_blank"
                                  className={`flex items-center justify-between gap-2 rounded-[7px] p-4 px-6 text-sm ${theme == "dark" ? "bg-[#1D1D1D]" : "bg-[#FAFAFA]"}`}
                                >
                                  <div className="flex items-center gap-2">
                                    <img
                                      className="h-10 w-10 object-cover"
                                      src="/DarkIcons/pdf_icons.png"
                                      alt=""
                                    />
                                    <div
                                      className={`w-full ${theme == "dark" ? "text-white" : "text-black"} max-w-56 overflow-hidden`}
                                    >
                                      {starMessage?.message_content
                                        ?.split("/")
                                        .pop()
                                        ?.split("-")
                                        .slice(1)
                                        .join("-") || ""}
                                    </div>
                                  </div>
                                  <img
                                    src="/DarkIcons/Download_icon.png"
                                    className="h-8 w-8 cursor-pointer"
                                    alt=""
                                  />
                                </a>
                              </div>
                            ) : starMessage.message_type === "audio" ? (
                              // <audio controls>
                              //   <source src={starMessage.Chat.url} type="audio/ogg" />
                              //   <source src={starMessage.Chat.url} type="audio/mpeg" />
                              //   Your browser does not support the audio element.
                              // </audio>
                              <AudioPlayer
                                src={starMessage.message_content}
                                minimal={true}
                                width={300}
                                trackHeight={50}
                                barWidth={3}
                                gap={1}
                                visualise={true}
                                backgroundColor={
                                  starMessage.sender_id == userData.user_id
                                    ? theme == "dark"
                                      ? "#FFEDAB"
                                      : "#FFEDAB"
                                    : theme == "dark"
                                      ? "#787878"
                                      : "#DDDDDD"
                                }
                                barColor="#CCCCCC"
                                barPlayedColor="#000"
                                skipDuration={2}
                                seekBarColor="black"
                                // volumeControlColor="blue"
                                hideSeekBar={true}
                                hideTrackKnobWhenPlaying={true}
                              />
                            ) : starMessage.message_type === "location" ? (
                              <div
                                className={`h-44 w-60 max-w-80 rounded-[9px] lg:h-48 lg:w-[16rem] ${starMessage.sender_id == userData.user_id ? "primary-gradient rounded-br-none" : "rounded-bl-none bg-pdfBg"} px-1 pt-1`}
                              >
                                <div className="mx-auto mt-1 h-32 w-56 lg:h-36 lg:w-60">
                                  <GoogleMapReact
                                    bootstrapURLKeys={{
                                      key: "AIzaSyAMZ4GbRFYSevy7tMaiH5s0JmMBBXc0qBA",
                                    }}
                                    defaultCenter={{
                                      lat: Number(
                                        starMessage.message_content.split(
                                          ",",
                                        )[0],
                                      ),
                                      lng: Number(
                                        starMessage.message_content.split(
                                          ",",
                                        )[1],
                                      ),
                                    }}
                                    defaultZoom={13}
                                    draggable={false}
                                  >
                                    <MdLocationPin className="text-3xl text-black" />
                                  </GoogleMapReact>
                                </div>
                                <div className="grid place-content-center">
                                  <a
                                    target="_blank"
                                    // href={`http://maps.google.com/maps?z=12&t=m&q=loc:${starMessage.message_content.split(",")[0]}+${starMessage.message_content.split(",")[1]}`}
                                    className="mt-2 w-full cursor-pointer font-medium"
                                  >
                                    View Location
                                  </a>
                                </div>
                              </div>
                            ) : starMessage.message_type === "call" ? (
                              // @ts-ignore
                              <CallInMessageList
                                // @ts-ignore
                                messageData={starMessage}
                              />
                            ) : (
                              starMessage.message_type
                            )}

                            {/* {starMessage.Chat.message_type == "audio" ||
                          starMessage.Chat.message_type == "video" ? (
                            ""
                          ) : (
                            <div
                              className={`pl-2 opacity-0 ${(starMessage.Chat.message_type == "image" || starMessage.Chat.message_type == "video") && "absolute right-3 top-3"} ${MessageOptions.selectMessage ? "" : "group-hover:opacity-100"}`}
                            >
                              <SelectedMessageOption
                                messageData={messageData}
                              />
                            </div>
                          )} */}
                          </div>

                          <div className={`mt-1 flex items-center gap-x-2`}>
                            <div className="text-xs text-lightText">
                              {formatTimeOnly(starMessage.createdAt)}
                            </div>
                            {/* {starMessage.sender_id == userData.user_id && (
                            <LiaCheckDoubleSolid
                              title={
                                starMessage.Chat.message_read == 1
                                  ? "Seen"
                                  : "Unseen"
                              }
                              className={`h-5 w-5 ${
                                starMessage.Chat.message_read == 1
                                  ? "text-[#9997EE]"
                                  : "text-gray-400"
                              } `}
                            />
                          )} */}
                            {true && (
                              <img
                                className="h-3 w-3"
                                src="/Home/Star - Iconly Pro.png"
                                alt=""
                              />
                            )}
                          </div>
                        </div>
                      </div>
                      {/* 
                      <img
                        src={starMessage.Chat.User?.profile_image}
                        alt="My profile"
                        className={`h-7 w-7 rounded-full object-cover ${
                          starMessage.Chat.senderId == userData.user_id
                            ? "order-2"
                            : "order-1"
                        } mt-auto ${
                          ["video", "image"].includes(
                            starMessage.Chat.message_type!,
                          )
                            ? "mb-7"
                            : "mb-5"
                        }`}
                      /> */}
                    </div>
                  </div>
                </>
              );
            })
          )}
        </>
      )}
    </div>
  );
}
