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

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

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

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

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

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

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

const fetchStaff = (value, callback) => {
  fetchResource(`/v1/users/staff`).then(({ body: { items }}) => {
    const options = items.map(item => ({ id: item.id, title: `${item.firstName} ${item.lastName}`}));
    callback(null, {options, complete: true});
  });
};

const ContractForm = reduxForm(formSettings)(
  class extends Component {
    createOrUpdate() {
      const { propertyId, formKey, values, actions, resetForm } = this.props;
      if (formKey === `add`) actions.linkContract(propertyId, values); resetForm();
      if (formKey !== `add`) actions.updateContract(propertyId, formKey, values);
    }
    unlink() {
      const { propertyId, formKey, actions } = this.props;
      actions.unlinkContract(propertyId, formKey);
    }
    render() {
      const {
        fields, values, propertyId, formKey, handleSubmit,
        pristine, error, submitting,
      } = this.props;
      return (
        <Table.Row>
          <Cell>
            <Grid.Row>
              <Col xs="15">
                <div className={cn(styles.selectWrapper, styles.pseudoPosition)}>
                  <Select asyncOptions={fetchStaff} {...fields.signedById} valueKey="id" labelKey="title" onBlur={() => {}} />
                </div>
              </Col>
            </Grid.Row>
          </Cell>
          <Cell>
            {formKey !== `add` && (<FormattedDate mask="dd.mm.yy @ HH:MM" value={values.createdAt} />)}
            {formKey === `add` &&
              <Group className={styles.resetMargin} kind={fields.file.touched && !!fields.file.error && `error`}>
                <Input type="file" {...fields.file} value={null} />
              </Group>
            }
          </Cell>
          <Cell>
            <Grid.Row>
              <Col xs="15">
                <Daypicker className={styles.daypicker} restrict="future"
                  control={<Input className={styles.inputDaypicker} {...fields.validFrom} type="text" />}
                  button={<Button className={styles.actionBtn} size="xs"><Icon className={styles.btnIcon} icon="calendar" /></Button>}
                  onDayClick={(day) => fields.validFrom.onBlur(day)}
                />
              </Col>
            </Grid.Row>
          </Cell>
          <Cell>
            <Grid.Row>
              <Col xs="15">
                <Daypicker className={styles.daypicker}
                  control={<Input className={styles.inputDaypicker} {...fields.validTo} type="text" />}
                  button={<Button className={styles.actionBtn} size="xs"><Icon className={styles.btnIcon} icon="calendar" /></Button>}
                  onDayClick={(day) => fields.validTo.onBlur(day)}
                />
              </Col>
            </Grid.Row>
          </Cell>
          {formKey !== `add` && (
            <Cell>
              <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>
              </Group>
            </Cell>
          )}
          {formKey === `add` && (
            <Cell>
              <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>
              </Group>
            </Cell>
          )}
        </Table.Row>
      );
    }
  }
);

class Contracts extends Component {
  componentWillMount() {
    const { propertyId, actions } = this.props;
    actions.loadContracts(propertyId);
  }
  render() {
    const { propertyId } = this.props;
    const contracts = this.props.state[propertyId] || [];
    console.log(contracts);
    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>
                <Heading>Действия</Heading>
              </Table.Row>
              <ContractForm {...this.props} formKey="add" />
              {contracts.map((item, index) => (
                <ContractForm {...this.props} key={index} formKey={item.id} initialValues={item} />
              ))}
            </Table.Container>
          </Col>
        </Grid.Row>
      </section>
    );
  }
}

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

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

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