import { useSyncEffect } from "@tingwu/common";
import { Controller, PID, TranslateMode } from "@tingwu/core";
import React, { memo, useCallback, useState } from "react";
import useForceUpdate from "use-force-update";
import { TYIcon } from "@tingwu/design";
import { Ellipsis } from "../ellipsis";
import { TranslateError } from "./styled";

interface TranslateStatusProps {
  controller: Controller;
  pid: PID;
}

type Status = "translating" | "error" | "normal";

export const TranslateStatus: React.FC<TranslateStatusProps> = memo(props => {
  const { controller, pid } = props;
  const [status, setStatus] = useState<Status>("normal");

  const translateMode = controller.getTranslateMode();
  const forceUpdate = useForceUpdate();

  useSyncEffect(() => {
    return controller.on("translateModeChange", forceUpdate);
  }, [controller, forceUpdate]);

  useSyncEffect(() => {
    return controller.on("fixParagraphTranslateChange", ({ translate }) => {
      if (pid === translate.pid) {
        if (translate.isTranslating) {
          setStatus("translating");
        } else if (translate.isTranslateError) {
          setStatus("error");
        } else {
          setStatus("normal");
        }
      }
    });
  }, [controller, pid]);

  const handleRetryTranslate = useCallback(() => {
    controller.emitParagraphNeedTranslate(pid);
  }, [controller, pid]);

  if (translateMode === TranslateMode.Disabled || status === "normal") {
    return null;
  }

  if (status === "error") {
    return (
      <TranslateError onClick={handleRetryTranslate}>
        <TYIcon type={"tongyi-refresh-line"} size={20} style={{ fontSize: 16 }} /> 翻译失败请重试
      </TranslateError>
    );
  }

  if (status === "translating") {
    return <Ellipsis />;
  }

  return null;
});
