import React, { useState } from "react";
import { ChatMessageActions } from "../ChatMessageActions/ChatMessageActions";
import { Menu } from "../../../../Menu";
import { Prompt } from "../../../../Prompt";
import { ChatMessageAvatar } from "../ChatMessageAvatar/ChatMessageAvatar";
import { ChatDeletedMessageType } from "../ChatDeleteMessageType/ChatDeletedMessageType";
import ChatDefaultMessageType from "../ChatDefaultMessageType/ChatDefaultMessageType";
import ChatEditedMessageType from "../ChatEditedMessageType/ChatEditedMessageType";
import ReplyIcon from "../../../../../assets/replyIcon.svg";
import EditIcon from "../../../../../assets/pencilIcon.svg";
import UnpinIcon from "../../../../../assets/unpinedIcon.svg";
import DeleteIcon from "../../../../../assets/deleteIcon.svg";
import "./ChatMessage.styles.scss";

export const ChatMessage = ({
  messageId,
  author,
  authorName,
  authorAvatar,
  content,
  timestamp,
  isUser = false,
  showActions = true,
  showAvatar = true,
  isDeleted = false,
  edited = false,
  deleted = false,
  onReply,
  onReact,
  onBookmark,
  onPin,
  pinned,
  onMore,
  onEdit,
  onMessageDelete,
  onRefetchMessages,
  type = "default",
  priority = "default",
  actions = [],
  className = "",
  onThreadClick,
  isThreadIconVisible,
  isPinChatIconvisible,
  isHighlighted = false,
  highlightColor = null,
}) => {
  const [moreOptionsAnchorEl, setMoreOptionsAnchorEl] = useState(null);
  const [moreOptionsMenuOpen, setMoreOptionsMenuOpen] = useState(false);
  // state for modal
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const moreOptionsOptions = [
    // {
    //   label: "Reply",
    //   value: "reply",
    //   icon: <img src={ReplyIcon} alt="reply" />,
    //   onClick: () => {
    //     console.log("Reply");
    //   },
    // },
    {
      label: "Edit",
      value: "edit",
      icon: <img src={EditIcon} alt="edit" />,
      onClick: () => {
        if (onEdit) {
          onEdit();
        }
        setMoreOptionsMenuOpen(false);
      },
    },
    // {
    //   label: "Unpin",
    //   value: "unpin",
    //   icon: <img src={UnpinIcon} alt="unpin" />,
    //   onClick: () => {
    //     console.log("Unpin");
    //   },
    // },
    {
      label: "Delete",
      value: "delete",
      icon: <img src={DeleteIcon} alt="delete" />,
      onClick: () => {
        handleDeleteClick();
      },
    },
  ];

  const handleDeleteClick = () => {
    setShowDeleteModal(true); // ✅ open modal instead of deleting immediately
    setMoreOptionsMenuOpen(false);
  };

  const handleMsgDelete = async (messageId) => {
    try {
      setDeleting(true);

      // Call the delete API
      if (onMessageDelete) {
        const response = await onMessageDelete(messageId);
        console.log("[ChatMessage] Message deleted successfully", response);
      }

      // Close modal
      setShowDeleteModal(false);
    } catch (err) {
      console.error("[ChatMessage] Delete failed:", err);
    } finally {
      setDeleting(false);
    }
  };

  const messageClass = `chat-message ${
    isUser ? "user-message" : "assistant-message"
  } ${isHighlighted ? "highlighted-message" : ""} ${className}`;

  const handleClickOnMoreOptions = (e) => {
    e.stopPropagation();
    setMoreOptionsAnchorEl(e.currentTarget);
    setMoreOptionsMenuOpen(true);
  };

  // Determine if message is deleted (check both isDeleted prop and deleted field)
  const isMessageDeleted = isDeleted || deleted;

  const messageTypes = {
    deleted: <ChatDeletedMessageType timestamp={timestamp} isUser={isUser} />,
    default: (
      <ChatDefaultMessageType
        content={content}
        timestamp={timestamp}
        priority={priority}
        edited={edited}
        handleClickOnMoreOptions={handleClickOnMoreOptions}
        onThreadClick={onThreadClick}
        isUser={isUser}
        pinned={pinned}
        visibility={moreOptionsMenuOpen}
        onPin={onPin}
        isThreadIconVisible={isThreadIconVisible}
        isPinChatIconvisible={isPinChatIconvisible}
        isHighlighted={isHighlighted}
        highlightColor={highlightColor}
      />
    ),
    editable: (
      <ChatEditedMessageType
        content={content}
        timestamp={timestamp}
        priority={priority}
        edited={edited}
        isUser={isUser}
        handleClickOnMoreOptions={handleClickOnMoreOptions}
        onThreadClick={onThreadClick}
        pinned={pinned}
      />
    ),
  };

  return (
    <div className={messageClass}>
      {showAvatar && !isUser && (
        <ChatMessageAvatar
          authorName={authorName}
          authorAvatar={authorAvatar}
        />
      )}

      <div className="message-content">
        {messageTypes[isMessageDeleted ? "deleted" : type]}
        <Menu
          anchorEl={moreOptionsAnchorEl}
          iconPlacement="top"
          open={moreOptionsMenuOpen}
          menuContainerClassName="more-options-menu"
          onClose={() => {
            console.log("onClose");
            setMoreOptionsMenuOpen(false);
          }}
          options={moreOptionsOptions}
          selected="Edit"
        />

        {/* {showActions && isUser && (
          <ChatMessageActions
            messageId={messageId}
            onReply={onReply}
            onReact={onReact}
            onBookmark={onBookmark}
            onPin={onPin}
            onMore={onMore}
            actions={actions}
          />
        )} */}
      </div>
      {/* ✅ Delete Confirmation Modal */}

      <Prompt
        handleClose={() => {
          setShowDeleteModal(false);
        }}
        isOpen={showDeleteModal}
        onPrimaryButtonClick={() => {
          handleMsgDelete(messageId);
        }}
        onSecondaryButtonClick={() => {
          setShowDeleteModal(false);
        }}
        primaryButtonLabel={deleting ? "Deleting..." : "Delete"}
        secondaryButtonLabel="Cancel"
        title="Are you sure"
        variant="error"
      >
        This will permanently delete message in this conversation.
      </Prompt>
    </div>
  );
};
