import { useState } from "react";
import { BsFillPinAngleFill } from "react-icons/bs";
import { FaChevronDown } from "react-icons/fa6";
import { HiOutlineDocumentText } from "react-icons/hi";
import { IoLocationOutline } from "react-icons/io5";
import { RiContactsLine } from "react-icons/ri";
import { Chat } from "../../../../types/ResType";
import useApiPost from "../../../../hooks/PostData";
import OnClickOutside from "../../../../utils/OnClickOutSide";
import toast from "react-hot-toast";
import ChatIcon from "/MessageListIcons/message.png";
import UnPinIcon from "/MessageListIcons/unpin_icon.png";
import PinIcon from "/MessageListIcons/pin 1.png";
import PinDarkIcon from "/MessageListIcons/pin_dark.png";
import UnPinDarkIcon from "/MessageListIcons/unpin_icon_dark.png";
import ChatDarkIcon from "/MessageListIcons/message_dark.png";
import { useAppDispatch } from "../../../../utils/hooks";
import { updateNavigateToSpesificMessage } from "../../../../store/Slices/NavigateToSpesificMessageSlice";
import { useTheme } from "../../../../context/ThemeProvider";
import { AiOutlineAudio } from "react-icons/ai";
import { useAppSelector } from "../../../../utils/hooks";
import { Message } from "../../../../types/MessageListType";
import ShowSavedName from "../../../../components/ShowSavedName";
import { getRandomColor } from "../../../../utils/getRandomColor";

export default function PinMessages() {
  const pinMessageData = useAppSelector(
    (state) => state.MessageList.pinned_messages.Records,
  );
  const [showPinMessageList, setshowPinMessageList] = useState(false);
  const { postData } = useApiPost();
  const dispatch = useAppDispatch();

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

  async function unpinMessage(messageData: Message) {
    await postData("chat/pin-unpin-message", {
      message_id: messageData.message_id,
      pin_lifetime: -1,
    });
    toast.success("Message Removed from Pin");
    // refetch pin messagelist
    // refetch();
  }

  function navigateToThatChat(messageData: Message) {
    setshowPinMessageList(false);
    dispatch(
      updateNavigateToSpesificMessage({
        chat_id: messageData.chat_id,
        navigate_to_message: true,
        message_id: messageData.message_id,
      }),
    );
  }

  return (
    <div className="absolute z-10 flex w-full select-none flex-col items-center justify-center">
      <OnClickOutside
        className="my-auto w-full"
        onClickOutside={() => {
          setshowPinMessageList(false);
        }}
      >
        <div
          onClick={() => {
            setshowPinMessageList(!showPinMessageList);
          }}
          className="flex w-full cursor-pointer justify-between bg-pinMessageListHeader p-3 px-4"
        >
          <div className="flex items-center gap-2">
            {/* <BsFillPinAngleFill className="text-xl" /> */}
            {/* <img
              className="h-5 w-5 theme-colored-icon"
              src={theme == "dark" ? PinDarkIcon : PinIcon}
              alt=""
            /> */}
            <div
              style={{
                maskImage: `url(${theme == "dark" ? PinDarkIcon : PinIcon})`,
                WebkitMaskImage: `url(${theme == "dark" ? PinDarkIcon : PinIcon})`,
              }}
              className="h-5 w-5 theme-colored-icon"
            ></div>
            {/* <DisplayPinMessages messageData={pinMessageData[0]} /> */}
            {pinMessageData.length} Pinned Messages
          </div>
          <div className="flex min-w-fit items-center gap-2">
            {/* {pinMessageData.length >= 2 && (
              <div>{pinMessageData.length} Messages </div>
            )} */}
            <FaChevronDown
              className={`my-auto ${showPinMessageList ? "rotate-180" : ""} transition-all duration-300`}
            />
          </div>
        </div>

        <div
          className={`mt-1 w-full ${showPinMessageList ? "block translate-y-0 opacity-100" : "hidden -translate-y-6 opacity-0"} transition-all overflow-auto max-h-96 duration-300`}
        >
          {pinMessageData.map((messageData) => {
            return (
              <>
                <div className="flex w-full justify-between border border-borderColor bg-pinMessageList p-2 px-4">
                  <div
                    onClick={() => {
                      navigateToThatChat(messageData);
                    }}
                    className="flex w-full cursor-pointer items-center gap-2"
                  >
                    <DisplayPinMessages messageData={messageData} />
                  </div>
                  <div className="flex items-center gap-4">
                    <div
                      onClick={() => {
                        unpinMessage(messageData);
                      }}
                      className={`grid h-10 w-10 cursor-pointer place-content-center rounded-full ${theme == "dark" ? "bg-[#3E3E3E]" : "bg-white"}`}
                    >
                      {/* <RiUnpinLine className="text-2xl text-black" /> */}
                      {/* <img
                        className="h-5 w-5"
                        src={theme == "dark" ? UnPinDarkIcon : UnPinIcon}
                        alt=""
                      /> */}
                      <div
                        style={{
                          maskImage: `url(${UnPinIcon})`,
                          WebkitMaskImage: `url(${UnPinIcon})`,
                        }}
                        className="h-5 w-5 theme-colored-icon"
                      ></div>
                    </div>
                    <div
                      onClick={() => {
                        navigateToThatChat(messageData);
                      }}
                      className={`grid h-10 w-10 cursor-pointer place-content-center rounded-full ${theme == "dark" ? "bg-[#3E3E3E]" : "bg-white"}`}
                    >
                      <div
                        style={{
                          maskImage: `url(${ChatDarkIcon})`,
                          WebkitMaskImage: `url(${ChatDarkIcon})`,
                        }}
                        className="h-5 w-5 theme-colored-icon"
                      ></div>
                    </div>
                  </div>
                </div>
                <hr className="border-t border-borderColor" />
              </>
            );
          })}
        </div>
      </OnClickOutside>
    </div>
  );
}

function DisplayPinMessages({ messageData }: { messageData: Message }) {
  console.log(messageData, "displayPinMessages");
  const { theme } = useTheme();
  return (
    <>
      <div>
        <div className="flex gap-3">
          <img
            src={messageData.User?.profile_pic}
            alt="My profile"
            className={`mt-auto h-7 w-7 rounded-full object-cover`}
          />

          <div
            style={{
              color: getRandomColor(messageData.User.user_name, theme),
            }}
            className={`my-auto text-sm`}
          >
            <ShowSavedName
              user_id={messageData.User.user_id.toString()}
              name={messageData.User.full_name}
            />
          </div>
        </div>
        <div className="ml-10 flex items-center gap-2">
          {messageData?.message_type == "image" ? (
            <>
              {/* <IoImageOutline className="fa fa-solid fa-image w-5 text-xl text-gray-500" />{" "} */}
              <img
                src={messageData?.message_content}
                className="h-24 w-24 rounded-md object-cover"
                alt=""
              />
            </>
          ) : messageData?.message_type == "gif" ? (
            <>
              <img
                src={messageData?.message_content}
                className="h-24 w-24 rounded-md object-cover"
                alt=""
              />
            </>
          ) : messageData?.message_type == "video" ? (
            <>
              <img
                src={messageData?.message_thumbnail}
                className="h-24 w-24 rounded-md object-cover"
                alt=""
              />
            </>
          ) : messageData?.message_type == "audio" ? (
            <>
              <AiOutlineAudio className="fa fa-solid fa-image w-5 text-lg" />
              Audio
            </>
          ) : messageData?.message_type == "doc" ? (
            <>
              <HiOutlineDocumentText className="h-5 w-5 text-lg" />
              Document
            </>
          ) : messageData?.message_type == "location" ? (
            <>
              <IoLocationOutline className="fa fa-solid fa-image w-5 text-lg text-gray-500" />
              Location
            </>
          ) : messageData?.message_type == "text" ? (
            <span className="line-clamp-1 w-full">
              {/* {truncateSentence(
                                                "lorem impus kkks kdj ks good morning good evening",
                                                28,
                                              )} */}
              {messageData?.message_content}
            </span>
          ) : messageData?.message_type == "link" ? (
            <>
              <span>🔗</span>
              <span className="line-clamp-1 w-full">
                {messageData?.message_content}
              </span>
            </>
          ) : messageData?.message_type == "contact" ? (
            <>
              <RiContactsLine />
              <span className="line-clamp-1">Contact</span>
            </>
          ) : (
            <div className="line-clamp-1 w-full">
              {messageData?.message_content}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
