import React, { Component } from 'react';
import PropTypes from 'prop-types';
import FileInput, { ListFiles } from '../FileInput';
import Cropper from '../Cropper';
import Modal, { Body } from '../Modal';
import { getInputProps } from '../_helpers/tools';

const propTypes = {
  placeHolder: PropTypes.string,
  sizes: PropTypes.array
};

const defaultProps = {
  placeHolder: 'You can drop your file(s) here',
  sizes: undefined
};

class ImageInput extends Component {
  state = {
    cropperImage: undefined
  };

  handleDrop = value => {
    this.handleEdit(value[0], 0);
  };

  handleEdit = (file, row) => {
    this.setState({
      cropperImage: file,
      cropperImageRow: row
    });
  };
  handleCrop = cropperData => {
    const { cropperImageRow } = this.state;
    const { value: [...value], onChange } = getInputProps(this.props);
    value[cropperImageRow] = cropperData;
    onChange(value);
    this.setState({
      cropperImage: undefined
    });
  };

  handleCancelCrop = () => {
    this.setState({
      cropperImage: undefined
    });
  };

  render() {
    const { placeHolder, sizes, ...props } = this.props;
    const { cropperImage } = this.state;
    return (
      <FileInput
        placeHolder={placeHolder}
        onDrop={this.handleDrop}
        {...props}
      >
        {({ value, handleDelete }) => value && !!value.length && (
          <ListFiles
            value={value}
            handleDelete={handleDelete}
            handleEdit={this.handleEdit}
          >
            {cropperImage && cropperImage.preview
              && <Modal isOpen size="lg">
                <Body>
                  <Cropper
                    value={cropperImage}
                    onCrop={this.handleCrop}
                    onCancelCrop={this.handleCancelCrop}
                    sizes={sizes}
                  />
                </Body>
              </Modal>
            }
          </ListFiles>
        )}
      </FileInput>
    );
  }
}

ImageInput.propTypes = propTypes;
ImageInput.defaultProps = defaultProps;

export default ImageInput;
