import { Controller, Selection } from "@tingwu/core";
import React, { memo, useCallback } from "react";
import { isEqual } from "lodash-es";
import { TagControlBar } from "../../../components/tagControlBar";
import { Wrapper } from "./styled";
import { report } from "../../../report";

interface ChromeContextMenuProps {
  controller: Controller;
  visible?: boolean;
  currentSelection: Selection;
}

export const ChromeContextMenu: React.FC<ChromeContextMenuProps> = memo(props => {
  const { controller, visible = true, currentSelection } = props;

  const setParagraphColor = useCallback(
    (color: string | undefined) => {
      // 2023.11.22, 如有最新选择内容，直接使用最新的。
      // 解决同一段落标记选择变更时候，由于 ChromeContextMenu 没有重新渲染导致 标记位置不对问题
      // AONE ID: 53294066
      const newSelection = controller.getCurrentSelection();
      controller.markSelectContents(newSelection ?? currentSelection, color);
      // 统计异常场景数量
      if (!isEqual(newSelection, currentSelection)) {
        report("fixed_origin_select_popover", {
          c5: currentSelection,
          c6: newSelection,
        });
      }
    },
    [controller, currentSelection]
  );

  const handleClickNail = useCallback(() => {
    setParagraphColor("blue");
  }, [setParagraphColor]);

  const handleClickQuestion = useCallback(() => {
    setParagraphColor("red");
  }, [setParagraphColor]);

  const handleClickTodo = useCallback(() => {
    setParagraphColor("yellow");
  }, [setParagraphColor]);

  const handleClickReset = useCallback(() => {
    setParagraphColor(undefined);
  }, [setParagraphColor]);

  if (!visible) {
    return null;
  }

  return (
    <Wrapper>
      <TagControlBar
        title="标记："
        onClickNail={handleClickNail}
        onClickQuestion={handleClickQuestion}
        onClickTodo={handleClickTodo}
        onClickReset={handleClickReset}
        useHover
      />
    </Wrapper>
  );
});
