import * as React from "react";
import { CURSOR_ID, EditorActions } from "../../types";
import { EditorObjectState } from "../EditorObject/types";
import { ItemLegendProps } from "./types";
import { EditorContext } from "../../Editor";
/**
 * A table of contents for the web page.
 */
export const ItemLegend: React.FC<ItemLegendProps> = ({
  children,
  content = [],
  title = "Your Components",
}) => {
  const editor = React.useContext(EditorContext);
  const { dispatch } = editor;

  return (
    <div data-testid="Editor-ItemLegend">
      <h2
        style={{
          marginTop: 0,
          // background: "white",
          // padding: "20px 0",
          padding: 10,
          textAlign: "center",
          width: 150,
        }}
      >
        {title}
      </h2>
      {content
        .filter((itm) => itm.id !== CURSOR_ID)
        .map((itm, key) => {
          const { id, state } = itm;
          return (
            <li
              key={key}
              style={{
                fontFamily: "Tahoma",
                fontSize: "11pt",
                listStyle: "none",
                cursor: "pointer",
                padding: "5px 20px",
                fontWeight:
                  itm.state === EditorObjectState.ACTIVE ? "bold" : "normal",
                color:
                  itm.state === EditorObjectState.HOVER ? "#666" : "inherit",
              }}
              data-testid="Editor-ItemObject-Item"
              onClick={(e) => {
                e.stopPropagation();
                editor.dispatch({
                  type: EditorActions.CHANGE_STATE,
                  payload: { id, state: EditorObjectState.ACTIVE },
                });
              }}
              onMouseEnter={(e) => {
                e.stopPropagation();
                if (state !== EditorObjectState.ACTIVE)
                  editor.dispatch({
                    type: EditorActions.CHANGE_STATE,
                    payload: { id, state: EditorObjectState.HOVER },
                  });
              }}
              onMouseLeave={(e) => {
                e.stopPropagation();
                if (state !== EditorObjectState.ACTIVE)
                  editor.dispatch({
                    type: EditorActions.CHANGE_STATE,
                    payload: { id, state: EditorObjectState.NORMAL },
                  });
              }}
            >
              {itm.type}
            </li>
          );
        })}
    </div>
  );
};

export default ItemLegend;
