import React from 'react';
import PropTypes from 'prop-types';
import {
  Card,
  Text,
  Button,
} from '@bufferapp/components';
import AppActionCreators from '../action-creators/AppActionCreators';
import ComposerActionCreators from '../action-creators/ComposerActionCreators';
import { addBlobIfNeeded, isSafari } from '../utils/DOMUtils';
import Modal from '../__legacy-buffer-web-shared-components__/modal/modal';
import InstagramThumbnailSlider from './InstagramThumbnailSlider';
import ComposerStore from '../stores/ComposerStore';
import styles from './css/InstagramThumbnailEditor.css';

class InstagramThumbnailEditor extends React.Component {
  static propTypes = {
    draftId: PropTypes.string.isRequired,
    video: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = { loading: false };
  }

  componentDidMount() {
    // though canvas is widely supported within browsers,
    // canvas.toBlob method isn't fully supported on Edge browsers
    addBlobIfNeeded();
  }

  setThumbnail = (draftId) => {
    const video = document.getElementById('thumbnailVideo');
    const canvas = document.getElementById('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    this.setState({
      loading: true,
    });
    AppActionCreators.setThumbnailLoading(true); // disables add to queue btn
    if (isSafari()) {
      // Need this for safari browsers because of a timing issue with drawImage
      canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
      setTimeout(() => {
        this.createUploadCanvasFile(canvas, video, draftId);
      }, 300);
    } else {
      this.createUploadCanvasFile(canvas, video, draftId);
    }
  }

  createUploadCanvasFile = (canvas, video, draftId) => {
    const draft = ComposerStore.getDraft(draftId);
    // draw image from video and format it to upload to AWS
    canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    canvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob);
      const imageFile = new File([blob], `${draft.video.name}_thumbnail.png`, { type: blob.type });
      imageFile.preview = url;
      ComposerActionCreators.uploadInstagramDraftThumbnail(draftId, imageFile, video);
    });
  }

  render() {
    const { draftId, video } = this.props;

    const btnWrapperStyle = {
      padding: '15px 0px',
    };

    const cardWrapperStyle = {
      maxHeight: '100vh',
      overflow: 'auto',
    };

    const modalClassNames = {
      modal: styles.modalStyles,
    };

    return (
      <div id="instagramThumbnail">
        <Modal classNames={modalClassNames}>
          <div style={cardWrapperStyle}>
            <Card noPadding>
              <div style={{ padding: '0px 10px' }}>
                <div style={{ padding: '15px 0px 7px' }}>
                  <Text>Select a frame from your video to save as your thumbnail.</Text>
                </div>
                <div className={styles.mediaContainer}>
                  <video
                    className={styles.media}
                    id="thumbnailVideo"
                    poster={video.thumbnail}
                    src={video.url}
                    crossOrigin="anonymous"
                    muted
                  />
                  <InstagramThumbnailSlider />
                  <canvas id="canvas" style={{ display: 'none' }} />
                  <div style={btnWrapperStyle}>
                    <Button
                      onClick={(e) => {
                        e.preventDefault();
                        this.setThumbnail(draftId);
                      }}
                    >
                      { this.state.loading ? 'Saving thumbnail...' : 'Save thumbnail' }
                    </Button>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </Modal>
      </div>
    );
  }
}

export default InstagramThumbnailEditor;
