import { Avatar } from "../Avatar";
import { Button } from "../Button";
import React, { useState, useMemo, useEffect } from "react";
import moment from "moment";
import { ReactComponent as MenuIcon } from "../../assets/MoreHorizontal.svg";
import { ReactComponent as SuccessIcon } from "../../assets/success-gray.svg";
import { ReactComponent as SuccessFillIcon } from "../../assets/success-fill.svg";
import { ReactComponent as SortIcon } from "../../assets/material-symbols_sort.svg";
import { ReactComponent as EmptyStateIcon } from "../../assets/commentEmptyStateIcon.svg";
import { Input } from "../Input";
import { ReactComponent as SearchIcon } from "../../assets/search.svg";
import { Menu } from "../Menu";
import { toInnerHTML } from "../../utils/html";
import { EmptyState } from "../EmptyState";
import { ReactComponent as NoFilterResultsIcon } from "../../assets/no-filter-results.svg";
import { getUserAvatarColor } from "../../utils/avatarColor";

// Static comment search options
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",
  // },
];

export default function CommentPanel({
  showCommentPanel,
  setShowCommentPanel,
  comments,
  onCommentItemClick,
  onMenuClick,
  onMarkAsReadClick,
  onMarkAsResolvedClick,
  commentProps,
  resolvedComments,
  popup,
  onShowResolvedCommentsRequest,
  onExitResolvedCommentsView,
}) {
  const [activeItem, setActiveItem] = useState(null);
  const [menuAnchorEl, setMenuAnchorEl] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedOption, setSelectedOption] = useState("opt1"); // Default to sort by date
  const [isLoadingResolvedComments, setIsLoadingResolvedComments] =
    useState(false);

  // Destructure configuration from commentProps
  const configuration = commentProps?.configuration || {};

  const filteredEntries = useMemo(() => {
    const entries = Object.entries(comments);
    if (!entries?.length) return [];

    const lower = (searchTerm || "").toLowerCase();
    const currentAuthor = commentProps?.author;

    // Apply text search filter
    let filtered = entries.filter(([key, value]) => {
      if (!lower) return true; // Show all if search is empty
      return value.some(
        (comment) =>
          comment.text?.toLowerCase?.().includes(lower) ||
          comment.author?.toLowerCase?.().includes(lower)
      );
    });

    // Apply filtering and sorting based on selected option
    const getTime = (entry) => {
      const ts = entry?.[1]?.[0]?.timestamp;
      const t = ts ? new Date(ts).getTime() : NaN;
      return Number.isNaN(t) ? -Infinity : t;
    };

    const isThreadUnread = (entry) => {
      const [key, value] = entry;
      // Check if the first comment in the thread is unread
      return value[0] && !value[0].isRead;
    };

    if (selectedOption === "opt1") {
      // Default: Sort by date - show all comments (both resolved and unresolved)
      // No additional filtering, just sort by date
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else if (selectedOption === "opt2") {
      // Sort by unread - show only unresolved comments and sort by unread status
      filtered = filtered.filter(([key, value]) => {
        const isResolved =
          Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved; // Show only unresolved comments
      });
      // Sort by unread (unread threads first, then by date)
      return filtered.sort((a, b) => {
        const unreadA = isThreadUnread(a);
        const unreadB = isThreadUnread(b);
        if (unreadA !== unreadB) {
          return unreadB - unreadA; // Unread threads first (true > false)
        }
        return getTime(b) - getTime(a); // Then by date (newest first)
      });
    } else if (selectedOption === "opt3") {
      // Show resolved comments - show only resolved comments
      filtered = filtered.filter(([key, value]) => {
        const isResolved =
          Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return isResolved; // Show only resolved comments
      });
      // Sort by date
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else if (selectedOption === "opt4") {
      // Only your threads - show only unresolved comments from current author
      filtered = filtered.filter(([key, value]) => {
        const isResolved =
          Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved; // Show only unresolved comments
      });
      // Filter by current author - only show threads started by current author
      if (currentAuthor) {
        filtered = filtered.filter(([key, value]) => {
          // Check if the first comment (thread starter) is from current author
          return value[0] && value[0].author === currentAuthor;
        });
      }
      // Sort by date
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    } else {
      // Fallback: show unresolved comments sorted by date
      filtered = filtered.filter(([key, value]) => {
        const isResolved =
          Array.isArray(resolvedComments) && resolvedComments.includes(key);
        return !isResolved; // Show only unresolved comments
      });
      return filtered.sort((a, b) => getTime(b) - getTime(a));
    }
  }, [
    comments,
    searchTerm,
    selectedOption,
    resolvedComments,
    commentProps?.author,
  ]);

  const handleSearchMenuClick = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };

  const handleSearchMenuClose = () => {
    setMenuAnchorEl(null);
  };

  const handleOptionClick = async (option) => {
    setMenuAnchorEl(null);

    // When switching away from "Show resolved comments" (opt3) to another option,
    // restore the original full comments so other sorting options work correctly
    if (
      selectedOption === "opt3" &&
      option.value !== "opt3" &&
      onExitResolvedCommentsView
    ) {
      onExitResolvedCommentsView();
    }

    if (option.value === "opt3" && onShowResolvedCommentsRequest) {
      setIsLoadingResolvedComments(true);
      try {
        await onShowResolvedCommentsRequest();
      } finally {
        setIsLoadingResolvedComments(false);
      }
    }
    setSelectedOption(option.value);
  };

  // Create options with onClick handlers and selection state
  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 (
    <div
      className={`comment-panel-main-container ${
        showCommentPanel ? "display-comment-panel" : ""
      }`}
    >
      <div className="comment-panel-header">
        <h2>Comments</h2>
        <span
          role="button"
          className="close_icon"
          onClick={(e) => {
            setShowCommentPanel(false);
            setSelectedOption("opt1");
            onExitResolvedCommentsView?.();
          }}
        />
      </div>
      <div className="comment-panel-body">
        {Object.keys(comments).length > 0 && (
          <div className="comment-panel-search-panel">
            <Input
              type="text"
              placeholder="Search comments"
              leftIcon={<SearchIcon />}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <Button
              className="sortIcon"
              size="small"
              variant="tertiary"
              disabled={false}
              icon={<SortIcon fontSize="small" />}
              iconPlacement="left"
              type="default"
              onClick={handleSearchMenuClick}
            />
          </div>
        )}
        {Object.keys(comments).length > 0 ? (
          <div className="comment-panel-content">
            {isLoadingResolvedComments ? (
              <EmptyState
                heading="Loading resolved comments..."
                description="Fetching resolved comments."
                emptyStateIcon={<NoFilterResultsIcon />}
              />
            ) : filteredEntries.length === 0 ? (
              <EmptyState
                heading="No results found"
                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={<NoFilterResultsIcon />}
              />
            ) : (
              filteredEntries.map(([key, value]) => {
                const isActive = activeItem === key;
                const timestamp = formatTimestamp(value[0].timestamp);
                const author = value[0]?.author;
                const isCurrentAuthor = commentProps?.author === author;
                const isRead = value[0]?.isRead ?? value[0]?.read;
                const isResolved =
                  Array.isArray(resolvedComments) &&
                  resolvedComments.find((comment) => comment === key);
                return (
                  <div
                    className={`comment-panel-item ${isActive ? "active" : ""}`}
                    key={key}
                    onClick={() => {
                      setActiveItem(key);
                      // if (value.length > 1)
                      onCommentItemClick(key, value);
                    }}
                  >
                    <div className="comment-panel-item-header">
                      <div className="comment-panel-item-header-left">
                        <div
                          style={{
                            position: "relative",
                            display: "inline-block",
                            padding: "2.5px 0px",
                          }}
                        >
                          <Avatar
                            size="small"
                            type="withoutPicture"
                            label={author}
                            style={{
                              width: "32px",
                              height: "32px",
                              borderRadius: "8px",
                              backgroundColor: getUserAvatarColor(author),
                            }}
                          />
                        </div>
                        <div className="comment-panel-author-info">
                          <span>{author}</span>
                          <span>
                            {timestamp}
                            {!isRead && !isResolved && (
                              <span
                                aria-label="unread"
                                style={{
                                  display: "inline-block",
                                  width: 8,
                                  height: 8,
                                  backgroundColor: "#E15554", // red
                                  borderRadius: "100%",
                                  verticalAlign: "middle",
                                  margin: "4px 0px 4px 6px",
                                }}
                              />
                            )}
                          </span>
                          {value[0].isEdited && <span>(edited)</span>}
                        </div>
                      </div>
                      <div className="comment-panel-item-header-right">
                        {!isResolved &&
                          !(
                            configuration?.disableMarkAsRead &&
                            configuration?.disableDeleteThread
                          ) && (
                            <Button
                              className="comment-panel-action-button"
                              size="small"
                              variant="text"
                              disabled={false}
                              icon={<MenuIcon fontSize="small" />}
                              iconPlacement="left"
                              type="text"
                              onClick={(e) => {
                                e.stopPropagation();
                                onMenuClick(e, key, "topMenu");
                              }}
                            />
                          )}
                        {!configuration?.disableMarkAsResolved && (
                          <div
                            onClick={(e) => {
                              if (isResolved) return;
                              e.stopPropagation();
                              if (onMarkAsResolvedClick)
                                onMarkAsResolvedClick(key, value);
                            }}
                            className="comment-panel-action-icon"
                          >
                            {isResolved ? (
                              <SuccessFillIcon fontSize="small" />
                            ) : (
                              <SuccessIcon fontSize="small" />
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                    <div
                      className="comment-panel-item-content"
                      dangerouslySetInnerHTML={toInnerHTML(value[0].text)}
                    />
                    {value.length > 1 && (
                      <div
                        className="comment-panel-item-footer"
                        onClick={() => onCommentItemClick(key, value)}
                      >
                        <span>{value.length - 1} replies</span>
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>
        ) : (
          <EmptyState
            heading="No comments to display"
            description="To add a new comment, simply click on any cell in the table and type your comment."
            emptyStateIcon={<EmptyStateIcon />}
          />
        )}
      </div>
      <Menu
        anchorEl={menuAnchorEl}
        iconPlacement="left"
        onClose={handleSearchMenuClose}
        open={Boolean(menuAnchorEl)}
        MenuProps={{
          sx: {
            zIndex: 9999,
          },
          anchorOrigin: {
            vertical: "bottom",
            horizontal: "right",
          },
          transformOrigin: {
            vertical: "top",
            horizontal: "right",
          },
        }}
        options={menuOptions}
        selected={{ value: selectedOption }}
      />
    </div>
  );
}
