import React, { memo, useState, useRef } from "react";
import { Controller, PID } from "@tingwujs/core";
import { useSyncEffect } from "@tingwujs/common";
import { StyledSelection } from "./styled";
import { isEqual } from "lodash";

export interface HSelectionProps {
  controller: Controller;
  pid: PID;
  containerRef: ReturnType<typeof useRef<HTMLDivElement | null>>;
  isHighlight: boolean;
}

export const HSelection: React.FC<HSelectionProps> = memo(props => {
  const { controller, pid, isHighlight } = props;

  const [styles, setStylesState] = useState<React.CSSProperties[]>([]);
  const stylesRef = useRef(styles);

  const setStyles = (v: React.CSSProperties[]) => {
    if (!isEqual(v, stylesRef.current)) {
      stylesRef.current = v;
      setStylesState(stylesRef.current);
    }
  };

  useSyncEffect(() => {
    setStyles(controller.getSelectionStyles(pid));
    return controller.on("selectionStylesChange", ({ styles: localStyles }) => {
      const selection = controller.getCurrentSelection();
      if (selection) {
        const startPid = selection.range.start.pid;
        const endPid = selection.range.end.pid;

        const inSelectedPid = pid >= startPid && pid <= endPid;
        if (inSelectedPid) {
          setStyles(localStyles[pid] || []);
        } else {
          setStyles([]);
        }
      } else {
        setStyles(localStyles[pid] || []);
      }
    });
  }, [controller, pid]);

  if (styles.length === 0) {
    return null;
  }

  return (
    <>
      {styles.map(style => (
        <StyledSelection isHighlight={isHighlight} style={style} />
      ))}
    </>
  );
});
