import Button from '../../button';
import Field from '..';
import Input from '../../input';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, connect } from 'react-redux';
import { combineReducers, createStore } from 'redux';
function formReducer(state = { email: 'frankqian@qq.com' }, action) {
  switch (action.type) {
    case 'save_fields':
      return {
        ...state,
        ...action.payload,
      };
    default:
      return state;
  }
}

interface IProps {
  dispatch: (action: any) => void;
  email?: string;
}

interface IState {
  formReducer: {
    email?: string;
  };
}

class Demo extends React.Component<IProps, IState> {
  field: Field;
  constructor(props) {
    super(props);

    this.field = new Field(this, {
      onChange: (name, value) => {
        console.log('onChange', name, value);
        this.field.setValue('newlen', value.length);
        this.props.dispatch({
          type: 'save_fields',
          payload: {
            [name]: value,
          },
        });
      },
    });
  }

  componentWillReceiveProps(nextProps) {
    this.field.setValues({
      email: nextProps.email,
      newlen: nextProps.email.length,
    });
  }

  setEmail() {
    this.props.dispatch({
      type: 'save_fields',
      payload: {
        email: 'qq@gmail.com',
      },
    });
  }

  render() {
    const init = this.field.init;

    const newLen = init('newlen', { initValue: this.props.email.length });

    return (
      <div>
        <Input
          {...init(
            'email',
            { initValue: this.props.email },
            {
              rules: [
                { required: true, type: 'email', message: 'at least 5 chars' },
              ],
            },
          )}
        />
        now length is:{newLen.value}
        <p>email: {this.props.email}</p>
        <Button onClick={this.setEmail.bind(this)}>set</Button>
      </div>
    );
  }
}

const ReduxDemo = connect((state: IState) => {
  return {
    email: state.formReducer.email,
  };
})(Demo);

const store = createStore(
  combineReducers({
    formReducer,
  }),
);

ReactDOM.render(
  <Provider store={store}>
    <div>
      <ReduxDemo />
    </div>
  </Provider>,
  document.getElementById('field-demo-7'),
);
