content: /* eslint-disable react/jsx-indent, linebreak-style */
  import React from 'react';
  import { connect } from 'react-redux';
  import { push } from 'react-router-redux';
  import Helmet from 'react-helmet';
  import { createStructuredSelector } from 'reselect';
  import Body from 'components/Body';
  import Regressivo from 'components/Regressivo';
  import Progressivo from 'components/Progressivo';
  import styles from './styles.css';
  import Button from 'components/Button';
  import LineChart from 'components/LineChart';
  import { Field, reduxForm } from 'redux-form/immutable';
  import RenderField from 'components/RenderField';
  import messages from './messages';
  import ToggleDisplay from 'react-toggle-display';
  import Header from 'components/Header';
  import { saveSimulation, fetchSimulationData, logout } from './actions';
  import {
    selectedDream,
    selectCurrentAge,
    selectAccumulated,
    selectInitialDeposit,
    selectPerMonth,
    selectAge,
    selectPerMonthValue,
    selectAgeValue,
    selectAccumulatedValue,
    selectFilled,
    selectInitialDepositValue,
    selectFinalValue,
    selectSaved,
    selectTaxIndicatorValue,
  } from './selectors';
  import { selectLocale } from '../LanguageProvider/selectors';
  
  const validate = (values, props) => {
    const errors = {};
    if (!values.get('age')) {
      errors.age = 'Obrigatório';
    } else if (parseInt(values.get('age'), 10) <= parseInt(props.currentAge, 10)) {
      errors.age = 'Should be less than current age';
    }
    if (!values.get('perMonth')) {
      errors.perMonth = 'Obrigatório';
    }
    if (!values.get('accumulated')) {
      errors.accumulated = 'Obrigatório';
    } else if (parseFloat(values.get('accumulated')) <= 0) {
      errors.accumulated = 'Obrigatório';
    }
    return errors;
  };
  
  export class SimulationPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
    constructor(props) {
      super(props);
      this.dream = props.dream;
      this.state = {
        popup: false,
      };
    }
  
    componentDidMount() {
      this.handleInitialize();
    }
  
    getStyles(classRefs) {
      const classes = [];
      classRefs.split(' ').forEach((className) => {
        classes.push(styles[className]);
      });
      return classes.join(' ');
    }
  
    handleInitialize() {
      let initData = {};
      if (this.props.filled) {
        initData = this.initialData();
        this.props.initialize(initData);
      } else {
        if (this.dream.planType === 'ACCUMULATED') {
          initData = {
            perMonth: 'NA',
            age: parseInt(this.dream.maturityAge, 10) - parseInt(this.props.currentAge, 10),
            accumulated: parseInt(this.dream.maturityValue, 10),
            initialDeposit: 0,
          };
        } else if (this.dream.planType === 'MONTHLY') {
          initData = {
            perMonth: parseInt(this.dream.fee, 10),
            age: parseInt(this.dream.tenure, 10),
            accumulated: 'NA',
            initialDeposit: 0,
          };
        }
        for (const key of Object.keys(initData)) {
          initData[key] = (initData[key]).toString();
        }
        this.props.fetchSimulationData(initData);
      }
    }
  
    initialData() {
      return {
        perMonth: this.props.perMonthValue,
        age: this.props.ageValue,
        accumulated: this.props.accumulatedValue,
        initialDeposit: this.props.initialDepositValue,
      };
    }
  
    openRoute = (route) => {
      this.props.changeRoute(route);
    };
  
    submit = (e) => {
      this.props.handleRoutes(e);
    };
  
    fetchValue = (e) => {
      const data = {};
      const name = e.target.name;
      const value = e.target.value;
      if (name === 'accumulated') {
        data.accumulated = value;
        data.perMonth = 'NA';
        data.initialDeposit = this.props.initialDeposit;
        data.age = this.props.age - this.props.currentAge;
      } else if (name === 'perMonth') {
        data.accumulated = 'NA';
        data.perMonth = value;
        data.age = this.props.age - this.props.currentAge;
        data.initialDeposit = this.props.initialDeposit;
      } else if (name === 'age') {
        data.accumulated = 'NA';
        data.perMonth = this.props.perMonth;
        data.age = value - this.props.currentAge;
        data.initialDeposit = this.props.initialDeposit;
      } else if (name === 'initialDeposit') {
        data.accumulated = 'NA';
        data.perMonth = this.props.perMonth;
        data.age = this.props.age - this.props.currentAge;
        data.initialDeposit = value;
      }
      if (this.props.valid) {
        for (const key of Object.keys(data)) {
          data[key] = (data[key]).toString();
          data[key] = data[key] === 'NA' || key === 'age' ? data[key] : (parseFloat((data[key].replace(/\D*/g, ''))) / 100).toString();
        }
        this.props.fetchSimulationData(data);
      }
    };
  
    goBack = () => {
      this.props.changeRoute('/recommendation');
    };
  
    togglePopup = () => {
      this.setState({
        popup: !this.state.popup,
      });
    };
  
    render() {
      const getValueFormat = value => {
        if (value) {
          return parseFloat((value.toString().replace(/\D*/g, '')) / 100).toLocaleString(this.props.locale, { minimumFractionDigits: 2 });
        }
        return '';
      };
      return (
        <article>
          <Helmet
            title="Simulation"
            meta={[
              { name: 'description', content: 'Bank of Brazil' },
            ]}
          />
          <Header
            title="Simular sonho"
            transparent
            back={this.goBack}
            noShadow
            logout={this.props.logout}
            advanced={this.togglePopup}
            upload
          />
          <Body collapsedTB collapsedSides>
            <div className={styles.banner}>
              <h1>{this.dream.dreamName}</h1>
              <form className={styles.form} onSubmit={this.props.handleSubmit(this.submit)}>
                <Body cozy collapsedTB>
                  <Field
                    component={RenderField}
                    className={'light center nopadding'}
                    type="text"
                    label={messages.accumulated}
                    name="accumulated"
                    placeholder="34,000,000"
                    blurAction={this.fetchValue}
                    format={getValueFormat}
                    unit="R$"
                  />
                </Body>
                <Body collapsedTB collapsedSides transparent>
                  <LineChart locale={this.props.locale} data={typeof this.props.futureValue === 'undefined' ? 'no data' : this.props.futureValue} />
                </Body>
                <Body cozy>
                  <section className={styles.row}>
                    <div className={styles.col}>
                      <Field
                        component={RenderField}
                        className={'left light'}
                        type="text"
                        name="perMonth"
                        placeholder="10,000"
                        label={messages.perMonth}
                        blurAction={this.fetchValue}
                        format={getValueFormat}
                        unit="R$"
                      />
                    </div>
                    <div className={styles.col}>
                      <Field
                        component={RenderField}
                        className={'left light'}
                        type="text"
                        name="age"
                        placeholder="55"
                        label={messages.age}
                        blurAction={this.fetchValue}
                        format={value => ((value) && (value < 0 ? value * -1 : value))}
                        unit="anos"
                        unitAtRight
                      />
                    </div>
                  </section>
                  <ToggleDisplay show={this.state.popup}>
                    <div className={styles.popup}>
                      <Field
                        component={RenderField}
                        type="text"
                        className={'dark left'}
                        name="initialDeposit"
                        label={messages.initialDeposit}
                        blurAction={this.fetchValue}
                        format={getValueFormat}
                        unit="R$"
                      />
                      <div className={styles.button}>
                        <Button
                          className="btn btn_secondary btn_ghost btn-block"
                          type="button"
                          handleRoute={() => {
                            this.setState({ popup: false });
                          }}
                        >Close</Button>
                      </div>
                    </div>
                  </ToggleDisplay>
                </Body>
                <Body white cozy>
                  <div className={styles.row}>
                    <div className={styles.col}>
                      <div className={styles.indicator}>
                        <span>Previdência </span>
                        <span>{this.props.taxIndicator}</span>
                      </div>
                    </div>
                    <div className={styles.col}>
                      <Button
                        className="btn btn_secondary" type="submit"
                        disabledButton={this.props.submitting || !this.props.valid}
                      >
                        Continuar
                      </Button>
                    </div>
                  </div>
                </Body>
              </form>
            </div>
          </Body>
          {(this.props.taxIndicator === 'VGBL Regressivo') ? <Regressivo /> : <Progressivo />}
        </article>
      );
    }
  }
  
  SimulationPage.propTypes = {
    handleSubmit: React.PropTypes.func,
    fetchSimulationData: React.PropTypes.func,
    name: React.PropTypes.string,
    age: React.PropTypes.string,
    submitting: React.PropTypes.bool,
    saved: React.PropTypes.bool,
    valid: React.PropTypes.bool,
    filled: React.PropTypes.bool,
    values: React.PropTypes.object,
    initialize: React.PropTypes.func,
    handleRoutes: React.PropTypes.func,
    logout: React.PropTypes.func,
    bind: React.PropTypes.func,
    dispatch: React.PropTypes.func,
    perMonth: React.PropTypes.string,
    initialDeposit: React.PropTypes.string,
    currentAge: React.PropTypes.string,
    accumulated: React.PropTypes.string,
    ageValue: React.PropTypes.string,
    initialDepositValue: React.PropTypes.string,
    perMonthValue: React.PropTypes.string,
    accumulatedValue: React.PropTypes.string,
    change: React.PropTypes.func,
    dreams: React.PropTypes.object,
    dream: React.PropTypes.number,
    futureValue: React.PropTypes.array,
    taxIndicator: React.PropTypes.string,
    locale: React.PropTypes.string,
  };
  
  const SimulationForm = reduxForm({
    form: 'Simulation',  // a unique identifier for this form
    validate,
  })(SimulationPage);
  
  SimulationPage.propTypes = {
    changeRoute: React.PropTypes.func,
  };
  
  function mapDispatchToProps(dispatch) {
    return {
      changeRoute: (url) => dispatch(push(url)),
      handleRoutes: (data) => dispatch(saveSimulation(data)),
      fetchSimulationData: (data) => dispatch(fetchSimulationData(data)),
      logout: (url) => dispatch(logout(url)),
      dispatch,
    };
  }
  
  const mapStateToProps = createStructuredSelector({
    saved: selectSaved(),
    filled: selectFilled(),
    dream: selectedDream(),
    currentAge: selectCurrentAge(),
    age: selectAge(),
    initialDeposit: selectInitialDeposit(),
    perMonth: selectPerMonth(),
    accumulated: selectAccumulated(),
    perMonthValue: selectPerMonthValue(),
    ageValue: selectAgeValue(),
    accumulatedValue: selectAccumulatedValue(),
    initialDepositValue: selectInitialDepositValue(),
    futureValue: selectFinalValue(),
    taxIndicator: selectTaxIndicatorValue(),
    locale: selectLocale(),
  });
  
  // Wrap the component to inject dispatch and state into it
  export default connect(mapStateToProps, mapDispatchToProps)(SimulationForm);
  