import React, { useState } from 'react';
import { Field } from 'react-final-form';
import classNames from 'classnames/bind';
import ModuleButton from 'components/items/ModuleButton';
import { required, email, composeValidators } from 'store/utils/validation';
import UploadZone from 'components/formItems/UploadZone';
import Checkbox from 'components/formItems/Checkbox';
import { config } from 'config/general';
import MultipleUploadZone from 'components/formItems/MultipleUploadZone';
import styleIdentifiers from './uploadCmsImageForm.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  onSubmit: Function;
}

export type UploadCmsImageFormProps = StateProps & DispatchProps & OwnProps;

const UploadCmsImageForm = (props: UploadCmsImageFormProps) => {
  const { handleSubmit, upload, submitting, valid, uploadS3, uploadApollo } = props;

  const [cropper, setCropper] = useState(false);

  function renderUpload() {
    if (config.api && config.api.uploadUrlApollo) {
      return uploadApollo;
    }
    if (config.cmsUploadS3) {
      return uploadS3;
    }
    return upload;
  }

  return (
    <form className={styles('UploadCmsImageForm')} onSubmit={handleSubmit}>
      <Field
        component={MultipleUploadZone}
        oneFile
        button={ModuleButton}
        name="image"
        type="picture"
        previewType="picture"
        validate={composeValidators(required)}
        className={styles('cropper')}
        displayValue={config.cmsUploadDisplayValue || 'large'}
        noResize={!cropper}
        s3Upload={config.cmsUploadS3}
        uploadParams={{ privateFile: false }}
        asObject
        uploadPrefix="content"
        upload={renderUpload()}
        uploadUrl={config.cmsUploadURL || 'uploads/getUploadUrl'}
        apollo={config.api.uploadUrlApollo}
        withLibrary
      />
      {!config.cmsUploadS3 && (
        <Field
          noMargin
          component={Checkbox}
          useBox
          activeClassName={styles('active')}
          type="checkbox"
          label="Enable Cropper"
          name="cropper"
          onChange={() => setCropper(!cropper)}
        />
      )}
      <ModuleButton disabled={submitting || !valid} label="Submit" type="submit" />
    </form>
  );
};

export default UploadCmsImageForm;
