import React, { memo, useState, useRef, Fragment, FC } from 'react';
import classNames from 'classnames';
import light from 'images/loading_light.webm';
import styles from './index.less';
import {getAssetsUrl} from 'utils/utils';

import defaultLoadPage from '../../../images/loading_background.jpg';

interface IProps {
  prepare?: boolean;
  percent?: number;
  children?: React.ReactElement;
  coverImg: string | null;
}

const LoadingProgress: FC<IProps> = ({ prepare = false, percent = 0, children, coverImg }) => {
  const [unmount, setUnmount] = useState(false);
  const containerRef = useRef(null);

  const handleTransitionEnd = (e) => {
    if (e.target === containerRef.current) {
      setUnmount(true);
    }
  };

  if (unmount) {
    return children || null;
  }

  percent = percent ? percent : 0;
  return (
    <div
      ref={containerRef}
      className={classNames(styles.container, { [styles.leave]: percent >= 100 })}
      style={{
        backgroundImage: coverImg ? `url(${getAssetsUrl(coverImg)})` : `url(${defaultLoadPage})`,
        position: window.location.pathname.includes('spaceShipEdit') ? 'relative' : 'fixed'
      }}
      onTransitionEnd={handleTransitionEnd}
    >
      {prepare ? (
        <div className={styles.text}>加载中...</div>
      ) : (
        <Fragment>
          <div className={styles.progress} style={{ width: `${percent}%` }} />
          <video className={styles.light} src={light} muted autoPlay loop style={{ left: `${percent}%` }} />
          <div className={styles.text}>加载中...{Math.floor(percent)}%</div>
        </Fragment>
      )}
    </div>
  );
};

export default memo(LoadingProgress);
