import { useState } from 'react';
import Player from 'react-player';
import { CircularProgress } from '@mui/material';
import isUndefined from 'lodash/isUndefined';

import { mergeProps } from '../Util';
import { styled } from '../Theme';

export interface VideoProps {
  url: string;
  width?: string | number;
  height?: string | number;
  style?: React.CSSProperties;
}

export default function Video(rawProps: VideoProps) {
  const props = Object.assign({}, rawProps);
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.width)) {
    props.width = 640;
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.height)) {
    props.height = 400;
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.style)) {
    props.style = {};
  }
  const newProps = mergeProps(props, Video, ['style']);
  const { url, width, height, style } = newProps;
  const [loaded, setLoaded] = useState(false);

  const styles = Object.assign({ border: 'none' }, style, {
    width,
    height,
    visibility: loaded ? 'visible' : 'hidden',
  });

  if (url.indexOf('v.qq.com') > 0) {
    return (
      <Placeholder style={{ width, height }}>
        <iframe title={url} style={styles} src={url} onLoad={() => setLoaded(true)} allowFullScreen />
        {!loaded && <CircularProgress className="loading-indicator" color="primary" />}
      </Placeholder>
    );
  }

  return (
    <Placeholder style={{ width, height }}>
      <Player style={styles} {...newProps} onReady={() => setLoaded(true)} />
      {!loaded && <CircularProgress className="loading-indicator" color="primary" />}
    </Placeholder>
  );
}

const Placeholder = styled('div')`
  background-color: #222222;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

  .loading-indicator {
    position: absolute;
    top: 45%;
    left: 47%;
    z-index: 2;
  }
`;
