import React, { Component } from 'react';
import { API } from 'cem/config/resources';

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as DocumentActions from 'cem/actions/properties/documents';

import { reduxForm } from 'redux-form';
// import { formFields } from 'cem/constants/documents';
// import validate from 'cem/validators/document';

import Select from 'react-select';
import { fetchResource } from 'cem/helpers/autocomplete';
import { FormattedDate } from 'react-formatted';

import styles from 'cem/styles/id/main';

import UI from 'cem/components/ui';
const {
  Grid: { Col },
  Table: { Heading, Cell },
  Form,
  Grid,
  Table,
  Button,
  Icon,
} = UI;

const formSettings = {
  form: `documentsOfProperties`,
  fields: [`kindId`, `file`, `createdAt`, `uploaderTitle`],
  // validate,
};

const fetchDocumentKinds = (input, callback) => {
  fetchResource(`/v1/dictionary/property_document_type`).then(({ body }) => {
    callback(null, { options: body.items }, { complete: true });
  });
};

const DocumentForm = reduxForm(formSettings)(
  class extends Component {
    createOrUpdate() {
      const { formKey, values, actions, propertyId, resetForm } = this.props;
      if (formKey === `add`) actions.linkDocument(propertyId, values); resetForm();
      if (formKey !== `add`) actions.updateDocument(propertyId, formKey, values);
    }
    unlink() {
      const { formKey, actions, propertyId } = this.props;
      actions.unlinkDocument(propertyId, formKey);
    }
    render() {
      const {
        formKey, fields, values, propertyId,

        handleSubmit,

        pristine,
        error,
        submitting,
      } = this.props;

      return (
        <Table.Row>
          <Table.Cell>
            <Form.Group className={styles.resetMargin} kind={fields.kindId.touched && !!fields.kindId.error && `error`}>
              <Select {...fields.kindId} asyncOptions={fetchDocumentKinds} labelKey="title" valueKey="id" onBlur={() => {}} />
              {fields.kindId.touched && fields.kindId.error && <Form.Helper>{fields.kindId.error}</Form.Helper>}
            </Form.Group>
          </Table.Cell>
          <Table.Cell>
            {formKey !== `add` && (
              <Grid.Row>
                {values.uploaderTitle}
              </Grid.Row>
          )}
          </Table.Cell>
          <Table.Cell>
            <Grid.Row>
              <Grid.Col xs="16">
                {formKey !== `add` && <FormattedDate mask="dd.mm.yy @ HH:MM" value={values.createdAt} />}
                {formKey === `add` &&
                  <Form.Group className={styles.resetMargin} kind={fields.file.touched && !!fields.file.error && `error`}>
                    <Form.Input type="file" {...fields.file} value={null} />
                    {fields.file.touched && fields.file.error && <Form.Helper>{fields.file.error}</Form.Helper>}
                  </Form.Group>
                }
              </Grid.Col>
            </Grid.Row>
          </Table.Cell>
          {formKey !== `add` && (
            <Table.Cell>
              <Form.Group className={styles.resetMargin}>
                <Button className={styles.actionBtn} size="xs" onClick={handleSubmit(::this.createOrUpdate)} disabled={pristine || error || submitting}>
                  <Icon className={styles.btnIcon} icon="checkmark" />
                </Button>
                <Button className={styles.actionBtn} size="xs" to={`${API}/v1/properties/${propertyId}/documents/${formKey}/download`} target="_blank">
                  <Icon className={styles.btnIcon} icon="download" />
                </Button>
                <Button className={styles.actionBtn} size="xs" onClick={handleSubmit(::this.unlink)}>
                  <Icon className={styles.btnIcon} icon="delete" />
                </Button>
              </Form.Group>
            </Table.Cell>
          )}
          {formKey === `add` && (
            <Table.Cell>
              <Form.Group className={styles.resetMargin}>
                <Button className={styles.actionBtn} size="xs" onClick={handleSubmit(::this.createOrUpdate)} disabled={pristine || error || submitting}>
                  <Icon className={styles.btnIcon} icon="checkmark" />
                </Button>
              </Form.Group>
            </Table.Cell>
          )}
        </Table.Row>
      );
    }
  }
);

class Documents extends Component {
  componentWillMount() {
    const { propertyId } = this.props;
    if (propertyId !== `create`) this.props.actions.loadDocuments(propertyId);
  }
  render() {
    const { propertyId } = this.props;
    const items = this.props.state[propertyId] || [];
    return (
      <section className={styles.wrapper}>
        <Grid.Row>
          <Col xs="20">
            <h2 className={styles.title}>Другие документы</h2>
          </Col>
        </Grid.Row>
        {/* <Grid.Row className={styles.pushedBottom}>
          <Col xs="20">
            <Button>Загрузить документ</Button>
          </Col>
        </Grid.Row> */}
        <Grid.Row>
          <Col xs="20">
            <Table.Container width="100%">
              <Table.Row>
                <Heading>Тип документа</Heading>
                <Heading>Загрузил</Heading>
                <Heading>Дата загрузки</Heading>
                <Heading>Действия</Heading>
              </Table.Row>
              <DocumentForm {...this.props} formKey="add" />
              {items.map(item => (
                <DocumentForm {...this.props} formKey={item.id} initialValues={item} />
              ))}
            </Table.Container>
          </Col>
        </Grid.Row>
      </section>
    );
  }
}

const pickState = ({ documentsByPropertyId }) => ({
  state: documentsByPropertyId,
});

const mapDispatch = (dispatch) => ({
  actions: bindActionCreators(DocumentActions, dispatch),
});

export default connect(pickState, mapDispatch)(Documents);
