import React from 'react';

import { admin as adminApi } from '@devcms/sdk';

class FieldFile extends React.Component {
  state = {
    url: null,
    filename: null,
    value: null,
  };

  constructor(props){
    super(props);

    this.state.value = props.value || '';

    this.handleFileChange = this.handleFileChange.bind(this);
    this.handleFileRemove = this.handleFileRemove.bind(this);
  }

  componentDidMount() {
    if (!this.state.value) {
      return;
    }

    adminApi.media.get(this.state.value).then(media => {
      this.setState({ filename: media.filename, url: media.url });
    }).catch(() => this.setState({ value: '' }));
  }

  handleFileChange(e) {
    this.setState({
      url: URL.createObjectURL(e.target.files[0]),
      filename: e.target.files[0].name
    });

    adminApi.media.upload({
      file: e.target.files[0]
    }).then(media => {
      this.setState({ value: media.id, filename: media.filename, url: media.url });
      this.props.onChange(this.props.name, media.id);
    });
  }

  handleFileRemove() {
    this.setState({ url: null, filename: null, value: null });
    this.props.onChange(this.props.name, '');
  }

  renderPreview() {
    return (
      <React.Fragment>
        <div className="input-file-wrapper">
          <div className="input-file-preview" style={({
            backgroundImage: 'url(' + this.state.url + ')'
          })}/>
          <button className="btn btn-small btn-red" onClick={this.handleFileRemove}>Remove</button>
        </div>
        <span className="label">{this.state.filename}</span>
      </React.Fragment>
    );
  }

  renderInput() {
    return (<input type="hidden" name={this.props.name} id={this.props.name} value={this.state.value} />);
  }

  renderUpload() {
    return (
      <React.Fragment>
        <label htmlFor={this.props.name + '-file'} className={ 'input-file-wrapper' + (this.state.url ? ' file-ok' : '')}>
          <span>Click to<br/>add new file</span>
          <input type="file" name={this.props.name + '-file'} id={this.props.name + '-file'} onChange={this.handleFileChange}/>
        </label>
      </React.Fragment>
    );
  }

  render() {
    return (
      <div className="box-content">
        <div className="columns">
          <div className="column-6">
            <div className="field field-info">
              <h3 className="field-info-title">{this.props.title}</h3>
              <p className="field-info-text">{this.props.desc}</p>
            </div>
          </div>
          <div className="column-6">
            <div className="field">
              <div className="input-file">
                {this.state.url ? this.renderPreview() : this.renderUpload()}
                {this.renderInput()}
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default FieldFile;

