import { GrPin } from "react-icons/gr";

import { Message } from "../../../../types/MessageListType";
import {
  updateMessageOptions,
  addMessage,
} from "../../../../store/Slices/MessageOptionsSlice";
import { useAppDispatch, useAppSelector } from "../../../../utils/hooks";
import toast from "react-hot-toast";
import useApiPost from "../../../../hooks/PostData";
import PinIcon from "/MessageListIcons/pin_outline.png";
import PinDarkIcon from "/MessageListIcons/pin_icon_outline_dark.png";
import UnPinIcon from "/MessageListIcons/unpin_icon.png";
import UnPinDarkIcon from "/MessageListIcons/unpin_icon_outline_dark.png";
import { useTheme } from "../../../../context/ThemeProvider";

interface Props {
  messageData: Message;
}

const PinMessageButton = ({ messageData }: Props) => {
  const dispatch = useAppDispatch();
  const pinMessageData = useAppSelector(
    (state) => state.MessageList.pinned_messages.Records,
  );
  const { loading, postData } = useApiPost();
  // @ts-ignore
  const { theme } = useTheme();

  // Check if the message is already pinned
  const isPinned = pinMessageData.some(
    (pin) => pin.message_id === messageData.message_id,
  );

  async function unpinMessage() {
    await postData("chat/pin-unpin-message", {
      message_id: messageData.message_id,
      pin_lifetime: -1,
    });
    toast.success("Message Removed from Pin");
    // refetch pin messagelist
  }
  return (
    <button
      onClick={() => {
        if (isPinned) {
          unpinMessage();
        } else {
          dispatch(updateMessageOptions({ show_pin_message_modal: true }));
          dispatch(addMessage(messageData));
        }
      }}
      className="group flex py-1.5 w-full items-center  px-4 justify-between gap-2 data-[focus]:bg-dropdownOptionHover"
    >
      <span>{isPinned ? "Unpin" : "Pin"}</span>
      <img
        className={`h-5 w-5`}
        src={
          theme == "dark"
            ? isPinned
              ? UnPinDarkIcon
              : PinDarkIcon
            : isPinned
              ? UnPinIcon
              : PinIcon
        }
        alt=""
      />
    </button>
  );
};

export default PinMessageButton;
