import {
  docBaseHooks,
  docTextPolishHooks,
  docTranslateHooks,
} from '../../../../../../documentModel';
import { TextPolishMode, TranslateMode } from '@tingwujs/core';
import { message, TYIcon } from '@tingwujs/design';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useDataHooks } from '../../../businessCommon/separateHooks/dataShare';
import { IconButton, Item, Label, LeftTopBarWrap, PopWindow } from './styled';

const LeftTopBar = () => {
  const [popIsVisible, setPopIsVisible] = useState(false);
  const [selectedId, setSelectedId] = useState(1);
  const popWindowRef = useRef<HTMLDivElement>(null);
  let timer: string | number | NodeJS.Timeout | undefined;
  const { docTranslateData } = docTranslateHooks.useDocTranslateData();
  const { docBaseData } = docBaseHooks.useDocBaseData();
  const { controller } = useDataHooks();
  const { docTextPolishData } = docTextPolishHooks.useDocTextPolishData();

  const openTranslate = useMemo(() => {
    return (
      docTranslateData?.originTranslate &&
      docTranslateData?.translateIsOpen &&
      docTranslateData?.translateTargetLanguage !==
        docTranslateData?.translateSourceLanguage
    );
  }, [docTranslateData]);

  const openTextPolish = useMemo(() => {
    return (
      docTextPolishData?.textPolishSwitch === 1 &&
      docTextPolishData?.textPolishedDoc
    );
  }, [docTextPolishData]);

  useEffect(() => {
    if (!openTranslate && openTextPolish) {
      setSelectedId(2);
    }
  }, [openTranslate, openTextPolish]);

  React.useEffect(() => {
    if (docTranslateData && selectedId === 1) {
      controller?.setTextPolishMode(TextPolishMode?.Disabled);
      if (openTranslate) {
        controller.setTranslateMode(TranslateMode.OriginAndTranslate);
        docTranslateData?.originTranslate?.pg?.map((item: any) => {
          const value = item.ts.map((_item: any) => {
            const _value: any = { ..._item };
            _value.tc = _item.txt;
            delete _value.txt;
            return _value;
          });
          controller.setTranslate(`${item.pi}`, value);
          return value;
        });
        controller.setTranslateMode(
          docTranslateData?.translateDisplayMode === 1
            ? TranslateMode.TranslateOnly
            : TranslateMode.OriginAndTranslate,
        );
      } else {
        controller.setTranslateMode(TranslateMode.Disabled);
      }
    }
    if (docTextPolishData && selectedId === 2) {
      controller.setTranslateMode(TranslateMode.Disabled);
      if (openTextPolish) {
        controller.setTextPolishMode(TextPolishMode.OriginAndTextPolish);
        docTextPolishData.textPolishedDoc?.forEach((textPolish) => {
          controller.setTextPolish(textPolish.pi, textPolish);
        });
      } else {
        controller?.setTextPolishMode(TextPolishMode?.Disabled);
      }
    }
  }, [
    docTranslateData?.originTranslate,
    docTranslateData?.translateTargetLanguage,
    docTextPolishData,
    selectedId,
  ]);

  React.useEffect(() => {
    if (docTranslateData) {
      if (
        !docTranslateData?.translateTargetLanguage ||
        docTranslateData?.translateTargetLanguage ===
          docTranslateData?.translateSourceLanguage
      ) {
        controller.setTranslateMode(TranslateMode.Disabled);
        const _res = docBaseData?.result;
        const OriginTranslate =
          typeof _res === 'string' ? JSON.parse(_res) : _res;
        OriginTranslate.pg?.map((item: any) => {
          const value = item.sc.map((_item: any) => {
            const _value: any = { ..._item };
            return _value;
          });
          controller.setTranslate(`${item.pi}`, value);
          return value;
        });
      }
    }
  }, [
    docTranslateData?.originTranslate,
    docTranslateData?.translateTargetLanguage,
  ]);

  React.useEffect(() => {
    if (
      docTranslateData?.translateBigModelTargetLoading === 1 &&
      docTranslateData?.translateOriginTargetLoading === 1
    ) {
      message.success({
        content: '翻译成功',
        key: 'tingwu2_translation_success',
      });
    } else if (
      (docTranslateData?.translateBigModelTargetLoading === 1 &&
        docTranslateData?.translateOriginTargetLoading === 2) ||
      (docTranslateData?.translateBigModelTargetLoading === 2 &&
        docTranslateData?.translateOriginTargetLoading === 1) ||
      (docTranslateData?.translateBigModelTargetLoading === 3 &&
        docTranslateData?.translateOriginTargetLoading === 1)
    ) {
      message.warning({
        content: '部分内容翻译失败，请重试',
        key: 'tingwu2_translation_warn',
      });
    } else if (
      docTranslateData?.translateBigModelTargetLoading === 2 &&
      docTranslateData?.translateOriginTargetLoading === 2
    ) {
      message.error({
        content: '翻译失败，请稍后重试',
        key: 'tingwu2_translation_fail',
      });
    }
  }, [
    docTranslateData?.translateBigModelTargetLoading,
    docTranslateData?.translateOriginTargetLoading,
  ]);
  const onMouseEnter = () => {
    timer && clearTimeout(timer);
    setPopIsVisible(true);
  };

  const onMouseLeave = () => {
    if (!popWindowRef.current) return;
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      setPopIsVisible(false);
    }, 100);
  };

  const onClick = (id: number) => {
    setSelectedId(id);
  };
  if (!openTranslate && !openTextPolish) {
    return null;
  }

  return (
    <LeftTopBarWrap>
      <IconButton onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
        <Label>{selectedId === 1 ? '翻译结果' : '口语书面化结果'}</Label>
        <TYIcon
          type={'icon-down-line'}
          style={{
            fontSize: 20,
            color: 'var(--Text_Primary)',
            transform: popIsVisible ? 'rotate(180deg)' : '',
            transition: 'transform 0.2s ease',
            cursor: 'pointer',
          }}
        />
        {popIsVisible && (
          <PopWindow
            onMouseEnter={onMouseEnter}
            onMouseLeave={onMouseLeave}
            ref={popWindowRef}
          >
            {openTranslate && (
              <Item onClick={() => onClick(1)} selected={selectedId === 1}>
                <div className="itemLabel">翻译结果</div>
                {selectedId === 1 && (
                  <TYIcon
                    type="icon-true-line"
                    style={{ fontSize: 20, color: 'var(--Fill_Brand_Primary)' }}
                  />
                )}
              </Item>
            )}
            {openTextPolish && (
              <Item onClick={() => onClick(2)} selected={selectedId === 2}>
                <div className="itemLabel">口语书面化结果</div>
                {selectedId === 2 && (
                  <TYIcon
                    type="icon-true-line"
                    style={{
                      fontSize: 20,
                      color: 'var(--Fill_Brand_Primary)',
                    }}
                  />
                )}
              </Item>
            )}
          </PopWindow>
        )}
      </IconButton>
    </LeftTopBarWrap>
  );
};

export default LeftTopBar;
