import React from 'react';

import Dropzone from 'react-dropzone';
import request from 'superagent';

import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

import RaisedButton from 'material-ui/RaisedButton';
import LoadingIndicator from '../LoadingIndicator';

const styles = {
	customWidth: {
		width: 150
	}
};

const UPLOAD_URL = 'http://54.190.49.213/index.php/api/Files/editAgentImage';

export default class UploadAgentImage extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
			showUploadComponent: false,
			uploading: false,
			uploadedFile: [],

			isUploadBtnDisabled: true
		};
	}

	onImageDrop(files) {
		this.setState({
			uploadedFile: files[0],
			isUploadBtnDisabled: false
		});
	}

	showComponent() {
		this.setState({showUploadComponent: true});
	}

	handleUpload() {
		this.setState({uploading: true});

		const upload = request.post(UPLOAD_URL)
      .field('agent_id', this.props.id)
      .field('file', this.state.uploadedFile);

		upload.end((err, response) => {
			this.setState({uploading: false});

			if (err) {
			} else {
				this.setState({
					uploadedFile: [],
					isUploadBtnDisabled: true,
					showUploadComponent: false
				});
				this.props.renderFilesAgain();
			}
		});
	}

	render() {
		if (!this.state.showUploadComponent) {
			return (<div onClick={this.showComponent.bind(this)}>
        <RaisedButton label="Upload Image" secondary={true} fullWidth={true} />
      </div>);
		}

		if (this.state.showUploadComponent == true && this.state.uploading == false) {
			return (
        <div>
          <div className="FileUpload">

            <Dropzone
              multiple={false}
              onDrop={this.onImageDrop.bind(this)}>
              <p>Drop an image or click to select a file to upload.</p>
            </Dropzone>

          </div>

          <div>
            {this.state.uploadedFile.length < 1 ? null :
              <div>
                <p>{this.state.uploadedFile.name}</p>
              </div>}
          </div>

          <RaisedButton label="Upload" disabled={this.state.isUploadBtnDisabled} secondary={true} onClick={this.handleUpload.bind(this)} />

        </div>);
		}

		if (this.state.uploading) {
			return (<div>
        <p>Uploading....</p>
        <LoadingIndicator />
      </div>);
		}
	}
}
