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 { documents } from 'cem/actions/users/id';

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, Form, 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: `documentsOfStaff`,
  fields: formFields,
  validate,
};

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

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

    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/users/staff/${this.props.resourceId}/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.resourceId);
  }

  render() {
    const { resourceId, state } = this.props;
    const { documentsByUserId } = state.users;
    const { isFetching, items = [] } = documentsByUserId[resourceId] || {};

    if (isFetching) {
      return <UI.Loading />;
    }

    return (
      <section>
        <h2 className={styles.title}>Документы</h2>

        <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 {...this.props} formKey="add" />

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

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

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

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