import { jsxs, jsx } from "react/jsx-runtime";
import { useState, useMemo, useEffect } from "react";
import moment from "moment";
import { getAssetUrl } from "../../utils/assetBase.js";
import { getUserAvatarColor } from "../../utils/avatarColor.js";
import { toInnerHTML } from "../../utils/html.js";
import { Avatar } from "../Avatar/index.js";
import { Button } from "../Button/index.js";
import { EmptyState } from "../EmptyState/index.js";
import { Input } from "../Input/index.js";
import { Menu } from "../Menu/index.js";
const EmptyStateIcon = getAssetUrl("icons/commentEmptyStateIcon.svg");
const SortIcon = getAssetUrl("icons/material-symbols_sort.svg");
const MenuIcon = getAssetUrl("icons/MoreHorizontal.svg");
const NoFilterResultsIcon = getAssetUrl("icons/no-filter-results.svg");
const SearchIcon = getAssetUrl("icons/search.svg");
const SuccessFillIcon = getAssetUrl("icons/success-fill.svg");
const SuccessIcon = getAssetUrl("icons/success-gray.svg");
const COMMENT_SEARCH_OPTIONS = [
  {
    label: "Sort by date",
    value: "opt1"
  },
  {
    label: "Sort by unread",
    value: "opt2"
  },
  {
    label: "Show resolved comments",
    value: "opt3"
  },
  {
    label: "Only your threads",
    value: "opt4"
  }
  // {
  //   label: "Only current page",
  //   value: "opt5",
  // },
];
function CommentPanel({
  showCommentPanel,
  setShowCommentPanel,
  comments,
  onCommentItemClick,
  onMenuClick,
  onMarkAsReadClick,
  onMarkAsResolvedClick,
  commentProps,
  resolvedComments,
  popup,
  onShowResolvedCommentsRequest
}) {
  const [activeItem, setActiveItem] = useState(null);
  const [menuAnchorEl, setMenuAnchorEl] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedOption, setSelectedOption] = useState("opt1");
  const [isLoadingResolvedComments, setIsLoadingResolvedComments] = useState(false);
  const configuration = (commentProps == null ? void 0 : commentProps.configuration) || {};
  const filteredEntries = useMemo(() => {
    const entries = Object.entries(comments);
    if (!entries.length) return [];
    const lower = (searchTerm || "").toLowerCase();
    const currentAuthor = commentProps == null ? void 0 : commentProps.author;
    let filtered = entries.filter(([key, value]) => {
      if (!lower) return true;
      return value.some(
        (comment) => {
          var _a, _b, _c, _d;
          return ((_b = (_a = comment.text) == null ? void 0 : _a.toLowerCase) == null ? void 0 : _b.call(_a).includes(lower)) || ((_d = (_c = comment.author) == null ? void 0 : _c.toLowerCase) == null ? void 0 : _d.call(_c).includes(lower));
        }
      );
    });
    const getTime = (entry) => {
      var _a, _b;
      const ts = (_b = (_a = entry == null ? void 0 : entry[1]) == null ? void 0 : _a[0]) == null ? void 0 : _b.timestamp;
      const t = ts ? new Date(ts).getTime() : NaN;
      return Number.isNaN(t) ? -Infinity : t;
    };
    const isThreadUnread = (entry) => {
      const [key, value] = entry;
      return value[0] && !value[0].isRead;
    };
    if (selectedOption === "opt1") {
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else if (selectedOption === "opt2") {
      filtered = filtered.filter(([key, value]) => {
        const isResolved = Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved;
      });
      return filtered.sort((a, b) => {
        const unreadA = isThreadUnread(a);
        const unreadB = isThreadUnread(b);
        if (unreadA !== unreadB) {
          return unreadB - unreadA;
        }
        return getTime(b) - getTime(a);
      });
    } else if (selectedOption === "opt3") {
      filtered = filtered.filter(([key, value]) => {
        const isResolved = Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return isResolved;
      });
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else if (selectedOption === "opt4") {
      filtered = filtered.filter(([key, value]) => {
        const isResolved = Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved;
      });
      if (currentAuthor) {
        filtered = filtered.filter(([key, value]) => {
          return value[0] && value[0].author === currentAuthor;
        });
      }
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else {
      filtered = filtered.filter(([key, value]) => {
        const isResolved = Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved;
      });
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    }
  }, [comments, searchTerm, selectedOption, resolvedComments, commentProps == null ? void 0 : commentProps.author]);
  const handleSearchMenuClick = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };
  const handleSearchMenuClose = () => {
    setMenuAnchorEl(null);
  };
  const handleOptionClick = async (option) => {
    setMenuAnchorEl(null);
    if (option.value === "opt3" && onShowResolvedCommentsRequest) {
      setIsLoadingResolvedComments(true);
      try {
        await onShowResolvedCommentsRequest();
      } finally {
        setIsLoadingResolvedComments(false);
      }
    }
    setSelectedOption(option.value);
  };
  const menuOptions = COMMENT_SEARCH_OPTIONS.map((option) => ({
    ...option,
    onClick: () => handleOptionClick(option),
    selected: selectedOption === option.value
  }));
  const formatTimestamp = (timestamp) => {
    if (!timestamp) return "";
    if (moment(timestamp).isValid()) {
      return moment.utc(timestamp).local().format("hh:mm A, MM-DD-YYYY");
    }
    return timestamp;
  };
  useEffect(() => {
    if (!popup) {
      setActiveItem(null);
    }
  }, [popup]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: `comment-panel-main-container ${showCommentPanel ? "display-comment-panel" : ""}`,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "comment-panel-header", children: [
          /* @__PURE__ */ jsx("h2", { children: "Comments" }),
          /* @__PURE__ */ jsx(
            "span",
            {
              className: "close_icon",
              role: "button",
              onClick: (e) => {
                setShowCommentPanel(false);
              }
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "comment-panel-body", children: [
          Object.keys(comments).length > 0 && /* @__PURE__ */ jsxs("div", { className: "comment-panel-search-panel", children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                leftIcon: /* @__PURE__ */ jsx("img", { alt: "", src: SearchIcon, style: { width: 20, height: 20, display: "block" } }),
                placeholder: "Search comments",
                type: "text",
                value: searchTerm,
                onChange: (e) => {
                  setSearchTerm(e.target.value);
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                className: "sortIcon",
                disabled: false,
                icon: /* @__PURE__ */ jsx("img", { alt: "", src: SortIcon, style: { width: 20, height: 20, display: "block" } }),
                iconPlacement: "left",
                size: "small",
                type: "default",
                variant: "tertiary",
                onClick: handleSearchMenuClick
              }
            )
          ] }),
          Object.keys(comments).length > 0 ? /* @__PURE__ */ jsx("div", { className: "comment-panel-content", children: isLoadingResolvedComments ? /* @__PURE__ */ jsx(
            EmptyState,
            {
              description: "Fetching resolved comments.",
              emptyStateIcon: /* @__PURE__ */ jsx(
                "img",
                {
                  alt: "",
                  src: NoFilterResultsIcon,
                  style: { maxWidth: 200, height: "auto", display: "block" }
                }
              ),
              heading: "Loading resolved comments..."
            }
          ) : filteredEntries.length === 0 ? /* @__PURE__ */ jsx(
            EmptyState,
            {
              description: selectedOption === "opt3" ? "No resolved comments to display." : searchTerm ? `We couldn't locate ${searchTerm}. Please try searching for something else.` : "We couldn't find any matching comments.",
              emptyStateIcon: /* @__PURE__ */ jsx(
                "img",
                {
                  alt: "",
                  src: NoFilterResultsIcon,
                  style: { maxWidth: 200, height: "auto", display: "block" }
                }
              ),
              heading: "No results found"
            }
          ) : filteredEntries.map(([key, value]) => {
            var _a, _b, _c;
            const isActive = activeItem === key;
            const timestamp = formatTimestamp(value[0].timestamp);
            const author = (_a = value[0]) == null ? void 0 : _a.author;
            (commentProps == null ? void 0 : commentProps.author) === author;
            const isRead = ((_b = value[0]) == null ? void 0 : _b.isRead) ?? ((_c = value[0]) == null ? void 0 : _c.read);
            const isResolved = Array.isArray(resolvedComments) && resolvedComments.find((comment) => comment === key);
            return /* @__PURE__ */ jsxs(
              "div",
              {
                className: `comment-panel-item ${isActive ? "active" : ""}`,
                onClick: () => {
                  setActiveItem(key);
                  onCommentItemClick(key, value);
                },
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "comment-panel-item-header", children: [
                    /* @__PURE__ */ jsxs("div", { className: "comment-panel-item-header-left", children: [
                      /* @__PURE__ */ jsx(
                        "div",
                        {
                          style: {
                            position: "relative",
                            display: "inline-block",
                            padding: "2.5px 0px"
                          },
                          children: /* @__PURE__ */ jsx(
                            Avatar,
                            {
                              label: author,
                              size: "small",
                              style: {
                                width: "32px",
                                height: "32px",
                                borderRadius: "8px",
                                backgroundColor: getUserAvatarColor(author)
                              },
                              type: "withoutPicture"
                            }
                          )
                        }
                      ),
                      /* @__PURE__ */ jsxs("div", { className: "comment-panel-author-info", children: [
                        /* @__PURE__ */ jsx("span", { children: author }),
                        /* @__PURE__ */ jsxs("span", { children: [
                          timestamp,
                          !isRead && !isResolved && /* @__PURE__ */ jsx(
                            "span",
                            {
                              "aria-label": "unread",
                              style: {
                                display: "inline-block",
                                width: 8,
                                height: 8,
                                backgroundColor: "#E15554",
                                // red
                                borderRadius: "100%",
                                verticalAlign: "middle",
                                margin: "4px 0px 4px 6px"
                              }
                            }
                          )
                        ] }),
                        value[0].isEdited && /* @__PURE__ */ jsx("span", { children: "(edited)" })
                      ] })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "comment-panel-item-header-right", children: [
                      !isResolved && !((configuration == null ? void 0 : configuration.disableMarkAsRead) && (configuration == null ? void 0 : configuration.disableDeleteThread)) && /* @__PURE__ */ jsx(
                        Button,
                        {
                          className: "comment-panel-action-button",
                          disabled: false,
                          icon: /* @__PURE__ */ jsx(
                            "img",
                            {
                              alt: "",
                              src: MenuIcon,
                              style: {
                                width: 20,
                                height: 20,
                                display: "block"
                              }
                            }
                          ),
                          iconPlacement: "left",
                          size: "small",
                          type: "text",
                          variant: "text",
                          onClick: (e) => {
                            e.stopPropagation();
                            onMenuClick(e, key, "topMenu");
                          }
                        }
                      ),
                      !(configuration == null ? void 0 : configuration.disableMarkAsResolved) && /* @__PURE__ */ jsx(
                        "div",
                        {
                          className: "comment-panel-action-icon",
                          onClick: (e) => {
                            if (isResolved) return;
                            e.stopPropagation();
                            if (onMarkAsResolvedClick) onMarkAsResolvedClick(key, value);
                          },
                          children: isResolved ? /* @__PURE__ */ jsx(
                            "img",
                            {
                              alt: "",
                              src: SuccessFillIcon,
                              style: {
                                width: 20,
                                height: 20,
                                display: "block"
                              }
                            }
                          ) : /* @__PURE__ */ jsx(
                            "img",
                            {
                              alt: "",
                              src: SuccessIcon,
                              style: {
                                width: 20,
                                height: 20,
                                display: "block"
                              }
                            }
                          )
                        }
                      )
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: "comment-panel-item-content",
                      dangerouslySetInnerHTML: toInnerHTML(value[0].text)
                    }
                  ),
                  value.length > 1 && /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: "comment-panel-item-footer",
                      onClick: () => onCommentItemClick(key, value),
                      children: /* @__PURE__ */ jsxs("span", { children: [
                        value.length - 1,
                        " replies"
                      ] })
                    }
                  )
                ]
              },
              key
            );
          }) }) : /* @__PURE__ */ jsx(
            EmptyState,
            {
              description: "To add a new comment, simply click on any cell in the table and type your comment.",
              emptyStateIcon: /* @__PURE__ */ jsx(
                "img",
                {
                  alt: "",
                  src: EmptyStateIcon,
                  style: { maxWidth: 200, height: "auto", display: "block" }
                }
              ),
              heading: "No comments to display"
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          Menu,
          {
            anchorEl: menuAnchorEl,
            iconPlacement: "left",
            MenuProps: {
              sx: {
                zIndex: 9999
              },
              anchorOrigin: {
                vertical: "bottom",
                horizontal: "right"
              },
              transformOrigin: {
                vertical: "top",
                horizontal: "right"
              }
            },
            open: Boolean(menuAnchorEl),
            options: menuOptions,
            selected: { value: selectedOption },
            onClose: handleSearchMenuClose
          }
        )
      ]
    }
  );
}
export {
  CommentPanel as default
};
