import FullScreenFrame from '@/components/FullScreenFrame';
import KFSpin from '@/components/KFSpin';
import { getLabelStudioUrl } from '@/services/developmentEnvironment';
import { to } from '@/utils/promise';
import {
  editorUrlKey,
  getSessionStorageItem,
  removeSessionStorageItem,
} from '@/utils/sessionStorage';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import './index.less';

export enum IframePageType {
  DatasetAnnotation = 'DatasetAnnotation', // 数据标注
  AppDevelopment = 'AppDevelopment', // 应用开发
  DevEnv = 'DevEnv', // 开发环境
}

const getRequestAPI = (type: IframePageType): (() => Promise<any>) => {
  switch (type) {
    case IframePageType.DatasetAnnotation:
      return getLabelStudioUrl;
    case IframePageType.AppDevelopment:
      return () => Promise.resolve({ code: 200, data: 'http://172.20.32.181:30080/' });
    case IframePageType.DevEnv:
      return () => Promise.resolve({ code: 200, data: getSessionStorageItem(editorUrlKey) || '' });
  }
};

type IframePageProps = {
  type: IframePageType;
  className?: string;
  style?: React.CSSProperties;
};

function IframePage({ type, className, style }: IframePageProps) {
  const [iframeUrl, setIframeUrl] = useState('');
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    requestIframeUrl();
    return () => {
      if (type === IframePageType.DevEnv) {
        removeSessionStorageItem(editorUrlKey);
      }
    };
  }, []);
  const requestIframeUrl = async () => {
    setLoading(true);
    const [res] = await to(getRequestAPI(type)());
    if (res && res.data) {
      setIframeUrl(res.data);
    } else {
      setLoading(false);
    }
  };

  const hideLoading = () => {
    setLoading(false);
  };

  return (
    <div className={classNames('kf-iframe-page', className)} style={style}>
      {loading && <KFSpin />}
      <FullScreenFrame url={iframeUrl} onload={hideLoading} onerror={hideLoading} />
    </div>
  );
}

export default IframePage;
