import { useSyncEffect } from "@tingwujs/common";
import { PID, Controller } from "@tingwujs/core";
import React, { memo, useState } from "react";
import { UnfixText } from "./styled";
import { DynamicDots } from "../dynamicDots";

interface UnfixSentenseProps {
  controller: Controller;
  emptyUnfix?: boolean;
  pid?: PID;
  isHighlight?: boolean;
}

export const UnfixSentense: React.FC<UnfixSentenseProps> = memo(props => {
  const { controller, emptyUnfix, pid, isHighlight = false } = props;
  const [unfixText, setUnfixText] = useState("");

  const allTextContent = controller.getAllTextContent().join("");

  useSyncEffect(() => {
    const content = controller.getUnfixContent();
    if (content) {
      setUnfixText(content);
    }
  }, [controller]);

  useSyncEffect(() => {
    return controller.on("unfixSentenseChange", ({ text }) => {
      if (emptyUnfix) {
        setUnfixText(text);
      } else {
        const p = controller.getParagraph(pid!);
        setUnfixText(p?.isUnfix ? text : "");
      }
    });
  }, [controller, pid, emptyUnfix]);

  const isEmpty = !allTextContent && !unfixText;

  const toRenderUnfixText = isEmpty ? <DynamicDots style={{ fontSize: 18 }} /> : unfixText;

  if (!toRenderUnfixText) {
    return null;
  }

  return <UnfixText isHighlight={isHighlight}>{toRenderUnfixText}</UnfixText>;
});
