import React, { useEffect, useRef, useState } from "react";
import { getAvatarColor } from "../../../modules/collaboration/functions/getAvatarColor";
import { KebabIcon } from "../../icons/ExportCommonIcons";
import { adjustHeight } from "./function/textAreaHeightAdjust";
import { getUserData } from "../../../functions/getUserData";
import { useParams } from "react-router-dom";
import { deleteCommentApi } from "../../../services/factoryBuilder/comments/deleteCommentApi";
import { addCommentsApi } from "../../../services/factoryBuilder/comments/addCommentsApi";
import { useCommentStore } from "../../../store/collaboration/useCommentStore";
import { useSelectedComment, useSocketStore } from "../../../store/builder/store";
import { getRelativeTime } from "./function/getRelativeTime";
import { editThreadTitleApi } from "../../../services/factoryBuilder/comments/editThreadTitleApi";
import { useVersionContext } from "../../../modules/builder/version/versionContext";


interface MessageProps {
  val: Reply | CommentSchema;
  // val: Reply | CommentSchema;
  i: number;
  setMessages?: React.Dispatch<React.SetStateAction<Reply[]>>
  setIsEditable?: React.Dispatch<React.SetStateAction<boolean>>
  setEditedThread?: React.Dispatch<React.SetStateAction<boolean>>
  setMode?: React.Dispatch<React.SetStateAction<'create' | 'edit' | null>>
  isEditable?: boolean;
  isEditableThread?: boolean
  editedThread?: boolean;
  mode?: 'create' | 'edit' | null
}

const Messages: React.FC<MessageProps> = ({ val, i, setMessages, mode, setIsEditable, setEditedThread, editedThread, isEditableThread, setMode }) => {

  const { comments, updateComment, updateReply, removeReply } = useCommentStore();
  const [openOptions, setOpenOptions] = useState(false);
  const { projectId } = useParams();
  const { threadSocket } = useSocketStore();
  const { userName, userId, organization } = getUserData();
  const [isEditComment, setIsEditComment] = useState(false)
  const { selectedComment, setCommentPositionState } = useSelectedComment();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();

  // input
  const [value, setValue] = useState<string>(
    "comment" in val ? val.comment : val.threadTitle
  );

  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const currentUser = "1";

  // const UserName = "username";

  useEffect(() => {
    if (textareaRef.current) adjustHeight(textareaRef.current);
  }, [value]);

  function handleCancelAction() {
    setCommentPositionState(null)
    setIsEditable && setIsEditable(true);
    setIsEditComment(false)
  }

  const handleSaveAction = async () => {

    if (!projectId || !selectedVersion) return

    if (isEditableThread && editedThread) {
      try {
        // const editThreadTitle = await editThreadTitleApi(projectId, (val as CommentSchema).threadId, value, selectedVersion?.versionId || "")
        // if (editThreadTitle.message == "ThreadTitle updated Successfully") {
        //   const editedThread: CommentSchema = {
        //     state: 'active',
        //     threadId: editThreadTitle.data.replyId,
        //     creatorId: userId,
        //     createdAt: getRelativeTime(editThreadTitle.data.createdAt),
        //     threadTitle: value,
        //     lastUpdatedAt: new Date().toISOString(),
        //     position: editThreadTitle.data.position,
        //     rotation: [0, 0, 0],
        //     comments: [],
        //   }
        //   updateComment((val as CommentSchema).threadId, editedThread)
        // }
        //  projectId, userId, threadTitle, organization, threadId
        const threadEdit = {
          projectId,
          userId,
          threadTitle: value,
          organization,
          threadId: (val as CommentSchema).threadId || selectedComment.threadId,
          versionId: selectedVersion?.versionId || ""
        }

        threadSocket.emit('v1:thread:updateTitle', threadEdit)
      } catch {
      }
    } else {
      if (mode === "edit") {
        try {
          // const editComments = await addCommentsApi(projectId, value, selectedComment?.threadId, (val as Reply).replyId,  selectedVersion?.versionId || "")
          // 
          // const commentData = {
          //   replyId: `${editComments.data?.replyId}`,
          //   creatorId: `${userId}`,
          //   createdAt: getRelativeTime(editComments.data?.createdAt),
          //   lastUpdatedAt: "2 hrs ago",
          //   comment: value,
          // }

          // updateReply((val as CommentSchema).threadId, (val as Reply)?.replyId, commentData);

          if (threadSocket) {
            //  projectId, userId, comment, organization, threadId
            const editComment = {
              projectId,
              userId,
              comment: value,
              organization,
              threadId: selectedComment?.threadId,
              commentId: (val as Reply).replyId ?? "",
              versionId: selectedVersion?.versionId || ""
            }


            threadSocket.emit("v1-Comment:add", editComment);
            setIsEditable && setIsEditable(true);
            setEditedThread && setEditedThread(false)
          }

        } catch {
        }
      }

    }
    // setValue("");
    setIsEditComment(false);
  }

  const handleDeleteAction = async (replyID: any) => {
    if (!projectId || !selectedVersion) return
    setOpenOptions(false);
    try {
      // const deletedComment = await deleteCommentApi(projectId, selectedComment?.threadId, (val as Reply).replyId ,  selectedVersion?.versionId || "")
      // 
      // if (deletedComment === "'Thread comment deleted Successfully'") {
      //   setMessages && setMessages(prev => prev.filter(message => message.replyId !== replyID));
      //   removeReply(val.creatorId, replyID)
      // }
      if (threadSocket && setMessages) {


        // projectId, userId, commentId, organization, threadId
        const deleteComment = {
          projectId,
          userId,
          commentId: (val as Reply).replyId,
          organization,
          threadId: selectedComment?.threadId,
          versionId: selectedVersion?.versionId || ""
        }
        setMessages(prev => {
          // 👈 logs the current state
          return prev.filter(message => message.replyId !== (val as Reply).replyId);
        });
        removeReply(selectedComment?.threadId, (val as Reply).replyId); // Remove listener after response


        threadSocket.emit("v1-Comment:delete", deleteComment);
      }
    } catch {

    }
  }

  const handleFocus = (e: React.FocusEvent<HTMLTextAreaElement>) => {
    requestAnimationFrame(() => {
      if (textareaRef.current) {
        const length = textareaRef.current.value.length;
        textareaRef.current.setSelectionRange(length, length);
      }
    });
  };

  return (
    <>
      {isEditComment ? (
        <div className="edit-container">
          <div className="input-container">
            <textarea
              placeholder="type here"
              ref={textareaRef}
              autoFocus
              value={value}
              onChange={(e) => setValue(e.target.value)}
              style={{ resize: "none" }}
              onFocus={handleFocus}
            />
          </div>
          <div className="actions-container">
            <div className="options"></div>
            <div className="actions">
              <button
                className="cancel-button"
                onClick={() => {
                  handleCancelAction();
                }}
              >
                Cancel
              </button>
              <button
                className="save-button"
                onClick={() => {
                  handleSaveAction();
                }}
              >
                Save
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="message-container">
          <div
            className="profile"
            style={{ background: getAvatarColor(i, userName) }}
          >
            {userName?.charAt(0).toUpperCase() || "user"}
          </div>
          <div className="content">
            <div className="user-details">
              <div className="user-name">{userName}</div>
              <div className="time">{isEditableThread ? getRelativeTime(val.createdAt) : val.createdAt}</div>
            </div>
            {(val as Reply).creatorId === userId && (
              <div className="more-options">
                <button
                  className="more-options-button"
                  onClick={() => {
                    setOpenOptions(!openOptions);
                  }}
                >
                  <KebabIcon />
                </button>
                {openOptions && (
                  <div className="options-list">
                    <button
                      className="option"
                      onClick={(e) => {
                        e.preventDefault();
                        setMode && setMode("edit")
                        setOpenOptions(false);
                        setEditedThread && setEditedThread(true);
                        setIsEditComment(true)
                      }}
                    >
                      Edit
                    </button>
                    {!(isEditableThread) && <button
                      className="option"
                      onClick={() => {
                        handleDeleteAction((val as Reply).replyId);
                      }}
                    >
                      Delete
                    </button>}
                  </div>
                )}
              </div>
            )}
            <div className="message">
              {"comment" in val ? val.comment : val.threadTitle}
            </div>
          </div>
        </div >
      )}
    </>
  );
};

export default Messages;
