import { h, Component } from 'preact';
import isEmail from 'validator/lib/isEmail';

import store from '../store';

import Form from './Form.jsx';
import Input from './Input.jsx';

import { login } from '../actions/user';
import { hideLoginModal } from '../actions/ui';

export default class LoginForm extends Form {
  constructor() {
    super();

    this.validation = {
      email: {
        required: true,
        tests: [
          [isEmail, 'Not a valid email'],
        ],
      },
      password: {
        required: true,
      },
    };

    this.state = {
      className: ['login-form', 'modal', 'enter', 'animate'],
    };

    this.onSubmit = this.onSubmit.bind(this);
  }

  componentWillMount() {
    this.unsubscribe = store.subscribe(() => this.forceUpdate());
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onSubmit(e) {
    e.preventDefault();

    if (!this.validate()) return;

    store.dispatch(login(this.toJSON()));
  }

  render() {
    const { ui } = store.getState();

    return ui.showLoginModal ? (
      <form
        className={this.state.className.join(' ')}
        onSubmit={this.onSubmit}
      >
        <button type="button" onClick={() => store.dispatch(hideLoginModal())}>Close</button>
        <h1>Login</h1>
        <Input ref={this.register('email')} type="text" name="email" placeholder="Email" />
        <Input ref={this.register('password')} type="password" name="password" placeholder="Password" />
        <button>Login</button>
      </form>
    ) : null;
  }
}
