import React, {Component} from 'react'
import {connect} from 'react-redux'
import styled from 'styled-components'
import Fields from 'components/fields/fields'
import FieldsTable from 'components/fields_table'
import Button from 'components/utils/button'
import auto_bind from 'common/auto_bind'
import {card} from 'common/styles'
import {array_from_hash} from 'common/utilities'
import {get_fields_by_value, get_values} from 'selectors/fields'
import {dismiss_front_modal} from 'components/architecture/modals'

class AssociatedValuesSettings extends Component {
  constructor(props) {
    super(props)
    auto_bind(this)
  }

  remove() {
    dismiss_front_modal()
    this.props.remove()
  }

  render() {
    const {fields, name, create_value_field, update} = this.props
    return (
      <Container>
        <Card>
          <Fields on_create={create_value_field}>
            {[
              {
                id: "name",
                name: "Nom",
                category: "comment",
                comment: name,
                on_submit_comment(name) {
                  update({name})
                },
                auto_focus: !name,
              },
              ...fields,
            ]}
          </Fields>
        </Card>
        <FieldsTable fields={fields} />
        <Button secondary onClick={this.remove}>
          Supprimer
        </Button>
      </Container>
    )
  }
}

export default connect(
  (state, {value_id}) => ({
    ...get_values(state)[value_id],
    fields: array_from_hash(get_fields_by_value(state)[value_id]),
  })
)(AssociatedValuesSettings)

const Card = styled.div`
  ${card}
`
const Container = styled.div`
  & > * {
    margin-bottom: 20px;
  }
`
