import React, { useRef, useCallback, useEffect, useState, ReactNode } from 'react';
import { useHistory } from 'react-router-dom';
import { request } from 'utils/fetch';
import { applyThemeOfScreen } from 'models/theme';
import { Status } from 'models/theme.types';
import { getTopScreenId } from 'utils/screen';
import EasyvModal from 'components/EasyvModal';
import { ConfirmRef } from 'components/EasyvModal/Confirm';
import { api } from 'constants/config';
import { Spin } from '@easyv/antd';
const { Confirm } = EasyvModal;
let timer;
const DELAY = 15000;

function EasyvScreenLock({ children, screenId, to }: { children?: ReactNode; screenId?: number; to?: string }) {
  const ref = useRef<ConfirmRef>(null);
  const history = useHistory();
  const screenTopId = screenId || getTopScreenId();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const monitorThemeStatus = () => {
    // 监控主题应用状态
    return request(api.screensThemeStatus, { id: screenTopId }).then((result) => {
      if (result && result?.status === Status.CancelTask) {
        timer && clearTimeout(timer);
      } else if (result && result.status === Status.StartTask) {
        if (!screenId) {
          timer = setTimeout(() => {
            monitorThemeStatus();
          }, DELAY);
        }
      }
      return result;
    });
  };

  useEffect(() => {
    // screenId 没有的时候，说明在screen edit 页面 反之 screenlist
    (async () => {
      const result = !screenId && (await monitorThemeStatus());
      if (result) {
        setVisible(result?.status === Status.StartTask);
      }
    })();

    return () => {
      timer && clearTimeout(timer);
    };
  }, []);

  useEffect(() => {
    visible ? ref.current?.show() : ref.current?.close();
  }, [visible]);

  const onOK = useCallback(() => {
    history.replace('/');
    setVisible(false);
  }, [history]);

  const onChange = async () => {
    if (loading) {
      return;
    }
    setLoading(true);
    const result = await monitorThemeStatus();
    setLoading(false);
    if (result?.status === Status.CancelTask) {
      //  状态正常
      to && history.push(to);
    }
    setVisible(result?.status === Status.StartTask);
  };

  return (
    <>
      <span onClick={onChange}>
        <Spin spinning={loading}>{children}</Spin>
      </span>
      <Confirm
        ref={ref}
        onOk={onOK}
        onCancel={async () => {
          await applyThemeOfScreen({
            screenId: screenTopId,
            status: Status.CancelTask
          });
          setVisible(false);
        }}
        cancelBtnType="danger"
        onOkBtnType="primary"
        cancelText="终止"
        okText="我知道了"
        title="可视化应用已锁定"
        content="该可视化应用正在执行主题包替换请稍后访问，替换完成后将自动解除锁定，或手动终止替换进程"
      />
    </>
  );
}

export default EasyvScreenLock;
