import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Container, ButtonContainer} from './styles.react.scss'
import CheckBox from 'components/utils/check_box'
import Button from 'components/utils/button'
import auto_bind from 'common/auto_bind'
import {property_toggler, scope} from 'common/utilities'
import {deal_has_custom_fields} from 'common/missions'
import {get_deals} from 'selectors/missions'
import {get_missions_fields, get_deals_fields} from 'selectors/fields'

class CustomizeDealFields extends Component {
  constructor(props) {
    super(props)
    const {has_custom_workplace, has_custom_events, custom_field_ids} = props.deal
    this.state = {
      has_custom_events,
      has_custom_workplace,
      custom_field_ids,
    }
    auto_bind(this)
  }

  toggle_custom_workplace() {
    this.setState(property_toggler('has_custom_workplace'))
  }

  toggle_custom_events() {
    this.setState(property_toggler('has_custom_events'))
  }

  toggle_custom_field(field_id) {
    this.setState(scope('custom_field_ids')(property_toggler(field_id)))
  }

  update() {
    this.props.update({...this.props.deal, ...this.state})
  }

  render_field({id, name, category, for_entity}) {
    let locked, selected = this.state.custom_field_ids[id]
    if (category == 'computed' || category == 'template') {
      locked = true
      switch (for_entity) {
        case 'Deal':
          selected = false
          break
        case 'Mission':
          selected = true
          break
      }
    }
    return (
      <CheckBox key={id} toggle={() => this.toggle_custom_field(id)} selected={selected} locked={locked}>
        {name}
      </CheckBox>
    )
  }

  render() {
    const {fields} = this.props
    const {has_custom_workplace, has_custom_events, custom_field_ids} = this.state
    return (
      <Container>
        <CheckBox toggle={this.toggle_custom_workplace} selected={has_custom_workplace}>
          Lieu de travail
        </CheckBox>
        <CheckBox toggle={this.toggle_custom_events} selected={has_custom_events}>
          Dates et horaires
        </CheckBox>
        {fields.map(this.render_field)}
        <ButtonContainer>
          <Button disabled={!deal_has_custom_fields(this.state)} onClick={this.update}>
            Valider
          </Button>
        </ButtonContainer>
      </Container>
    )
  }
}

export default connect(
  (state, {deal_id}) => ({
    deal: get_deals(state)[deal_id] || {custom_field_ids: {}},
    fields: [...get_missions_fields(state), ...get_deals_fields(state)],
  })
)(CustomizeDealFields)
