import React, {Component} from 'react'
import {connect} from 'react-redux'
import classNames from 'classnames/bind'
import Button from 'components/utils/button'
import UserCard from 'components/user_card'
import store from '../common/store'
import {user_full_name} from '../common/users'
import {get_demands} from '../selectors/demands'
import {alert_success} from '../actions/display'

const cx = classNames.bind(require('../styles/demands.scss'))

class DemandsStatic extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mode: 'pending',
    }
    this.render_demand = this.render_demand.bind(this)
    this.render_mode = this.render_mode.bind(this)
    this.set_mode = this.set_mode.bind(this)
  }

  set_mode(mode) {
    return () => this.setState({mode})
  }

  render_demand({id, ...demand}) {
    return (
      <Demand key={id} {...demand} mode={this.state.mode} />
    )
  }

  render_mode({label, mode}) {
    return (
      <div
        key={mode}
        onClick={this.set_mode(mode)}
        className={cx('demands__mode', {'demands__mode_selected': mode == this.state.mode})}>
        {label}
      </div>
    )
  }

  render() {
    let demands = this.props[this.state.mode]
    return (
      <div className={cx('demands')}>
        <div className={cx('demands__modes')}>
          {[
            {label: "En attente", mode: "pending"},
            {label: "Rejetées", mode: "rejected"},
          ].map(this.render_mode)}
        </div>
        <div className={cx('demands__table')}>
          {demands.map(this.render_demand)}
        </div>
      </div>
    )
  }
}

class Demand extends Component {
  constructor(props) {
    super(props)
    this.accept = this.accept.bind(this)
    this.reject = this.reject.bind(this)
  }

  accept() {
    this.props.accept()
    store.dispatch(alert_success(`Nous avons prévenu ${user_full_name(this.props.user)} que vous acceptez sa candidature.`))
  }

  reject() {
    this.props.reject()
    store.dispatch(alert_success(`Nous avons prévenu ${user_full_name(this.props.user)} que vous rejetez sa candidature.`))
  }

  render() {
    return (
      <div className={cx('demands__demand')}>
        <UserCard {...this.props.user} />
        {this.props.mode == "pending" ? (
          <Button onClick={this.reject} secondary>
            Rejeter
          </Button>
        ) : null}
        <Button onClick={this.accept} secondary={this.props.mode == "rejected"}>
          Accepter
        </Button>
      </div>
    )
  }
}

const Demands = connect(
  (state) => ({
    ...get_demands(state),
  })
)(DemandsStatic)

export default Demands
