import React, { Component } from 'react';

import HTML5Backend from 'react-dnd-html5-backend';
import { DragDropContext } from 'react-dnd';

import { reduxForm } from 'redux-form';
import constants from 'cem/constants/properties';
const { formFields } = constants;

import Uploadcare from 'cem/components/uploadcare';

import {PhotoCard, LayoutCard } from './photos/card';

import cn from 'classnames';
import styles from 'cem/styles/id/main';
import UI from 'cem/components/ui';
const {
  Grid: { Row, Col },
  Form, Button, Loading,
} = UI;

const formSettings = {
  form: `property`,
  fields: formFields,
};

class PhotoList extends React.Component {

  reorder(oldIndex, newIndex) {
    const { value, items } = this.props;
    const item = Object.assign({}, value[oldIndex]);
    items.removeField(oldIndex);
    items.addField({}, newIndex);
    Object.keys(item).map((key) => {
      items[newIndex][key].onChange(item[key]);
    });
  }

  remove(index) {
    const { items } = this.props;
    items.removeField(index);
  }

  handleUpload(src) {
    const { propertyId, upload } = this.props;
    upload(propertyId, src);
  }

  render() {
    const { Card } = this.props;
    const { items = [], isUploading } = this.props;
    return (
      <section className={styles.wrapper}>
        <Row>
          <Col xs="20">
            <h2 className={styles.title}>
              {this.props.title}
              <Uploadcare onChange={::this.handleUpload} onBlur={() => {}} />
              {isUploading && (<Loading />)}
            </h2>
          </Col>
        </Row>
        <Row>
          {items.map((item, index) => (
            <Col xs="4" key={index}>
              <Card {...item} index={index} reorder={::this.reorder} remove={::this.remove} />
            </Col>
          ))}
        </Row>
      </section>
    );
  }
}

export default DragDropContext(HTML5Backend)(reduxForm(formSettings)(
  class extends Component {
    update() {
      const { formKey, values, actions } = this.props;
      actions.updateProperty(formKey, values);
    }
    render() {
      const {
        fields, values, formKey,
        pristine, handleSubmit, actions,
      } = this.props;
      return (
        <Form.Container>
          <Row>
            <section className={styles.section}>
              <PhotoList propertyId={formKey} Card={PhotoCard} title="Фотографии" items={fields.images} value={values.images} isUploading={values.isPhotoUploading} upload={actions.uploadPhoto} />
              <PhotoList propertyId={formKey} Card={LayoutCard} title="Планировки" items={fields.layouts} value={values.layouts} isUploading={values.isLayoutUploading} upload={actions.uploadLayout} />
            </section>
          </Row>
          {formKey !== `create` && <Button className={cn(styles.btnSave, { [styles.btnHidden]: pristine })} onClick={handleSubmit(::this.update)} kind="warning" size="md" block>Сохранить</Button>}
        </Form.Container>
      );
    }
  }
));
