import React, { Component } from 'react';

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

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

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

import cn from 'classnames';
import styles from 'cem/styles/id/main';
import UI from 'cem/components/ui';
const { Table, Grid, Button, Icon } = UI;

const validate = (values) => {
  const errors = {};

  if (!values.linkedContactId) errors.linkedContactId = `Укажите контакт!`;
  if (!values.kindId) errors.kindId = `Укажите роль!`;

  return errors;
};

const formSettings = {
  form: `contatsOfProperty`,
  fields: contactFields,
  validate,
};

const fetchContacts = (input, callback) => {
  fetchResource(`/v1/contacts`).then(({ body }) => {
    callback(null, { options: body.items.map((item) => ({
      value: item.id, label: `${item.details.lastName} ${item.details.firstName} ${item.details.middleName}`,
    })), complete: true });
  });
};

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

const ContactForm = reduxForm(formSettings)(
  class extends Component {
    createOrUpdate() {
      const { propertyId, formKey, values, actions, resetForm } = this.props;
      if (formKey === `add`) actions.linkContact(propertyId, values); resetForm();
      if (formKey !== `add`) actions.updateLinkedContact(propertyId, formKey, values);
    }
    unlink() {
      const { propertyId, formKey, actions } = this.props;
      actions.unlinkContact(propertyId, formKey);
    }
    render() {
      const { formKey, fields, values, handleSubmit } = this.props;
      return (
        <Table.Row>
          <Table.Cell>
            <Select asyncOptions={fetchContacts} {...fields.linkedContactId} onBlur={() => {}} />
          </Table.Cell>
          <Table.Cell>
            {values.phoneNumber}
          </Table.Cell>
          <Table.Cell>
            <Grid.Row>
              <Grid.Col sm="14">
                <div className={cn(styles.selectWrapper, styles.pseudoPosition)}>
                  <Select asyncOptions={fetchContactKinds} {...fields.kindId} onBlur={() => {}} valueKey="id" labelKey="title" />
                </div>
              </Grid.Col>
            </Grid.Row>
          </Table.Cell>
          <Table.Cell>
            {formKey === `add` && (
              <Button className={styles.tableBtn} size="xs" onClick={handleSubmit(::this.createOrUpdate)}>
                <Icon className={styles.btnIcon} icon="checkmark" />
              </Button>
            )}
            {formKey !== `add` && (
              <Button className={styles.tableBtn} size="xs" onClick={handleSubmit(::this.unlink)}>
                <Icon className={styles.btnIcon} icon="delete" />
              </Button>
            )}
            {formKey !== `add` && (
              <Button className={styles.tableBtn} size="xs" onClick={handleSubmit(::this.createOrUpdate)}>
                <Icon className={styles.btnIcon} icon="arrow-left" />
              </Button>
            )}
          </Table.Cell>
        </Table.Row>
      );
    }
  }
);

class Contacts extends Component {
  componentWillMount() {
    const { propertyId, actions } = this.props;
    actions.loadLinkedContacts(propertyId);
  }
  render() {
    const { propertyId, state } = this.props;
    const items = state[propertyId] || [];
    return (
      <section className={this.props.className}>
        <Grid.Row>
          <Grid.Col xs="20" className={styles.wrapper}>
            <h2 className={styles.title}>Контакты</h2>
            <Table.Container width="100%">
              <Table.Row>
                <Table.Heading>Контакт</Table.Heading>
                <Table.Heading>Телефон</Table.Heading>
                <Table.Heading>Роль</Table.Heading>
                <Table.Heading>Действия</Table.Heading>
              </Table.Row>
              <ContactForm {...this.props} formKey="add" />
              {items.map(item => (
                <ContactForm {...this.props} formKey={item.linkedContactId} initialValues={item} />
              ))}
            </Table.Container>
          </Grid.Col>
        </Grid.Row>
      </section>
    );
  }
}

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

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

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