const { currentUser } = useLocalAuth();
export default function useComment() {
  class MComment implements TCommentChat {
    _id?: string;
    comment: string;
    attachments?: TAttachment[];
    createdBy: string;
    workOrder: string;
    createdAt?: string;
    updatedAt?: string;
    createdByName?: string;
    createdByType?: string;
    feedback?: string;
    justify?: string | undefined;
    seenByNames: string;

    constructor(comment: Partial<TCommentChat> = {}) {
      this._id = comment._id || "";
      this.comment = comment.comment || "";
      this.attachments = comment.attachments || [];
      this.workOrder = comment.workOrder || "";
      this.createdAt = comment.createdAt
        ? comment.createdAt.toString()
        : undefined;
      this.updatedAt = comment.updatedAt || "";
      this.createdBy = comment.createdBy || "";
      this.createdByName = comment.createdByName || "";
      this.createdByType = comment.createdByType || "";
      this.justify = comment.justify || "";
      this.feedback = comment.feedback || "";
      this.seenByNames = comment.seenByNames ?? "";
    }
  }

  const comment = useState("comment", () => new MComment());
  const comments = useState("comments", (): TCommentChat[] => []);
  const page = useState("commentPage", () => 1);
  const itemsPerPage = useState("itemsPerPage", () => 2);
  const search = useState("commentSearch", () => "");
  const pageRange = useState("commentPageRange", () => "-- - -- of --");
  const isCommentsLoaded = useState("isCommentsLoaded", () => false);

  function addComment(payload: TCommentChat) {
    delete payload._id;
    return useNuxtApp().$api<{ value?: { message: string } }>(
      "/api/comments/v1",
      {
        method: "POST",
        body: JSON.stringify(payload),
      }
    );
  }

  function getCommentById(id: string) {
    return useNuxtApp().$api(`/api/auth/comments/id/${id}`, {
      method: "GET",
    });
  }

  function setComment(data?: TCommentChat) {
    comment.value = new MComment(data);
  }

  const isInviteValid = useState("isInviteValid", () => false);

  function getCommentsByWorkOrder(id: string) {
    return useNuxtApp().$api(`/api/comments/v1/work-order/${id}`);
  }

  function getCommentsByWorkOrderId(id: string) {
    return useNuxtApp().$api(`/api/comments/v1/work-order/${id}`);
  }

  function getCommentsByFeedBackId(id: string, type?: string) {
    const commentFeedbackOrWOD =
      type === "workOrder" ? "work-order" : "feedback";
    return useNuxtApp().$api(`/api/comments/v1/${commentFeedbackOrWOD}/${id}`);
  }

  async function setComments(id: string, type?: string) {
    try {
      isCommentsLoaded.value = true;
      const _comments = (await getCommentsByFeedBackId(
        id,
        type
      )) as TCommentPaginated;

      let updateSeenIds: any = [];

      comments.value = _comments.items
        .map((comment: any) => {
          if (comment.createdBy === currentUser.value._id) {
            comment.justify = "end";
          } else {
            comment.justify = "start";
            if (
              ((Array.isArray(comment.seenBy) &&
                !comment.seenBy.includes(currentUser.value._id)) ||
                !comment?.seenBy) &&
              comment?._id
            ) {
              updateSeenIds.push(comment._id);
            }
          }
          return comment;
        })
        .sort(
          (firstComment: any, secondComment: any) =>
            new Date(firstComment.createdAt).getTime() -
            new Date(secondComment.createdAt).getTime()
        );

      if (Array.isArray(updateSeenIds) && updateSeenIds.length > 0) {
        const seenBy = await updateSeenBy(updateSeenIds, currentUser.value._id);
      }
    } catch (error) {
      console.log("error :", error);
    } finally {
      isCommentsLoaded.value = false;
    }
  }

  function updateSeenBy(ids: string[], seenById: string) {
    return useNuxtApp().$api(`/api/comments/v1/seen-by`, {
      method: "PUT",
      body: { seenById, ids },
    });
  }

  return {
    comment,
    comments,
    page,
    itemsPerPage,
    pageRange,
    addComment,
    setComment,
    search,
    isCommentsLoaded,
    isInviteValid,
    setComments,
    getCommentById,
    getCommentsByWorkOrderId,
    updateSeenBy,
    getCommentsByFeedBackId,
  };
}
