import React, { memo, useEffect, useMemo, useState } from "react";
import { StyledCaret } from "./styled";
import { useSyncEffect } from "@tingwu/common";
import { Controller } from "@tingwu/core";
import { useRecoilValue } from "recoil";
import { isReadonlyState } from "../../../model";

export interface PureCaretProps {
  controller: Controller;
  style?: React.CSSProperties;
  isHighlight?: boolean;
}

export const PureCaret: React.FC<PureCaretProps> = memo(props => {
  const { controller, style, isHighlight = false } = props;
  const [isHidden, setIsHidden] = useState(false);
  const isReadonly = useRecoilValue(isReadonlyState);

  useSyncEffect(() => {
    return controller.on("caretPendingChange", ({ caretPending }) => {
      if (caretPending) {
        setIsHidden(false);
      }
    });
  }, [controller]);

  useEffect(() => {
    const interval = setInterval(() => {
      if (controller.isCaretPending()) {
        setIsHidden(false);
      } else {
        setIsHidden(p => !p);
      }
    }, 500);
    return () => {
      clearInterval(interval);
    };
  }, [controller]);

  const calcedStyle: React.CSSProperties = useMemo(() => {
    return {
      ...style,
      opacity: isHidden || isReadonly ? "0" : "1",
    };
  }, [style, isHidden, isReadonly]);

  return <StyledCaret style={calcedStyle} isHighlight={isHighlight} />;
});
