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

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

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as ContactActions from 'cem/actions/contacts';

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 { Form, Grid, Table, Button, Icon } = UI;

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

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

const actions = {
  createDocument: ContactActions.createDocument,
  deleteDocument: ContactActions.deleteDocument,
  updateDocument: ContactActions.updateDocument,
};

const DocumentForm = reduxForm(formSettings, () => {}, actions)(
  class extends Component {
    createOrUpdate(values) {
      const { formKey, createDocument, updateDocument, contactId, resetForm } = this.props;

      if (formKey === `add`) {
        createDocument(contactId, values).then(resetForm);
      } else {
        updateDocument(contactId, formKey, values);
      }
    }

    remove() {
      const {formKey, deleteDocument, contactId} = this.props;

      deleteDocument(contactId, formKey);
    }

    render() {
      const {
        formKey, fields, values,

        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>
            <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>
          <Table.Cell>
            <Form.Group className={styles.resetMargin}>
              <Form.Input className={styles.tableInput} type="text" placeholder="Добавить комментарий" {...fields.comment} />
            </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>
                <Button className={styles.actionBtn} size="xs" to={`${API}/v1/contacts/${this.props.contactId}/documents/${formKey}/download`} target="_blank">
                  <Icon className={styles.btnIcon} icon="download" />
                </Button>
                <Button className={styles.actionBtn} size="xs">
                  <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() {
    this.props.actions.loadDocuments(this.props.contactId);
  }

  render() {
    const { items = [] } = this.props.state;

    return (
      <Table.Container width="100%">
        <Table.Row>
          <Table.Heading width="25%">Тип документа</Table.Heading>
          <Table.Heading width="30%">Дата загрузки</Table.Heading>
          <Table.Heading width="35%">Комментарий</Table.Heading>
          <Table.Heading width="10%">Действия</Table.Heading>
        </Table.Row>
        <DocumentForm contactId={this.props.contactId} formKey="add" />

        {items.map(item => <DocumentForm key={item.id} contactId={this.props.contactId} formKey={item.id.toString()} initialValues={item} />)}
      </Table.Container>
    );
  }
}

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

const pickActions = (dispatch) => ({
  actions: bindActionCreators(ContactActions, dispatch),
});

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