content: import React from 'react'
  import { Link } from 'react-router'
  import { connect } from 'react-redux'
  import { firebaseConnect, helpers } from 'react-redux-firebase'
  import { Container, Row, Col, ButtonGroup, Button } from 'reactstrap'
  import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'
  
  // Components
  import PageHeading from 'components/helper/PageHeading'
  import Loading from 'components/helper/Loading'
  import SimpleList from 'components/lists/simple'
  import RecentActionsList from 'components/lists/recent-actions-list'
  import DateTime from 'components/helper/DateTime'
  import ActionModal from 'components/modals/action'
  import GoalModal from 'components/modals/goal'
  import Feature from 'components/feature'
  import BackButton from 'components/buttons/back'
  import ConfirmationModal from 'components/modals/confirmation'
  import GoalPartners from 'components/goals/partners'
  
  // Helpers
  import DH from 'utils/DatabaseHelper'
  
  // Actions
  import { addAction, updateAction, markActionDone, deleteAction, updateGoal, deleteGoal } from 'actions/FirebaseActions'
  
  import TH from 'utils/TranslationHelper'
  
  const content = defineMessages({
    createdOn: { id: 'app.general.createdOn', defaultMessage: 'Created on' },
    primaryOn: { id: 'app.goal.single.primaryOn', defaultMessage: 'Selected as primary on' },
    desiredOutcome: { id: 'app.goal.single.desiredOutcome', defaultMessage: "Desired Outcome" },
    evidenceProcedure: { id: 'app.goal.single.evidenceProcedure', defaultMessage: "Evidence Procedure" },
    reasons: { id: 'app.goal.single.reasons', defaultMessage: "Reasons" },
    deadline: { id: 'app.goal.single.deadline', defaultMessage: "Deadline" },
    editGoal: { id: 'app.goal.single.editGoal', defaultMessage: "Edit goal" },
    recentlyCompletedActions: { id: 'app.goal.single.recentlyCompletedActions', defaultMessage: "Recently completed actions" },
    deleteGoal: { id: 'app.goal.single.deleteGoal', defaultMessage: "Delete goal" },
  })
  
  const populates = [
    DH.populate('goalPartner')
  ]
  @firebaseConnect((props) => ([
    { path: DH.goals(props.params.id), populates },
    DH.actionsByGoal(props.params.id, `goal_${props.params.id}_actions`)
  ]))
  @connect(({ firebase }, props) => ({
    auth: helpers.pathToJS(firebase, 'auth'),
    goal: helpers.populatedDataToJS(firebase, DH.goals(props.params.id), populates),
    goalActions: helpers.dataToJS(firebase, `goal_${props.params.id}_actions`)
  }))
  class GoalContainer extends React.Component {
    state = {
      modal: false,
      goalModal: false,
      goalFields: [
        { name: 'text', component: 'input' },
        { name: 'outcome', component: 'textarea' },
        { name: 'deadline', component: 'input', type: 'date' },
        { name: 'evidenceProcedure', component: 'textarea' },
        { name: 'reasons', component: 'textarea' },
      ],
      item: null,
      actionsFilters: [
        function(item) { return item.done === true }
      ],
      actionsSort: [
        (o) => { return o.priority },
        (o) => { return o.cdate }
      ],
      sortOrder: [
        "desc",
        "asc"
      ],
      actions: [
        { func: this.actionDone.bind(this), image: 'verification-checkmark-symbol' },
        { func: this.toggle.bind(this), image: 'pencil-edit' }
      ],
    }
  
    toggle (item) {
      if (this.state.modal === true) {
        this.setState({ modal: false, item: null })
      } else {
        this.setState({ modal: true, item: item })
      }
    }
  
    toggleGoalModal () {
      this.setState({ goalModal: ! this.state.goalModal, item: null })
    }
  
    actionDone (item) {
      markActionDone(item.key)
    }
  
    actionDelete () {
      deleteAction(this.props.params.id, this.state.item.key)
      this.toggle()
    }
  
    goalModalSubmit (form) {
      let updates = {}
  
      this.state.goalFields.forEach((field) => {
        if (form[field.name] === undefined) return
        updates[field.name] = form[field.name]
      })
  
      updateGoal(this.props.params.id, updates)
  
      this.toggleGoalModal()
    }
  
    actionModalSubmit (form) {
      let editedAction = { ...form }
      editedAction.priority = parseInt(editedAction.priority)
      delete editedAction.key
  
      if (form.key === undefined) {
        addAction(this.props.params.id, editedAction)
      } else {
        updateAction(form.key, editedAction)
      }
  
      this.toggle()
    }
  
    toggleConfirmationModal () {
      this.setState({ ...this.state, confirmationModal: !this.state.confirmationModal })
    }
  
    deleteGoal () {
      deleteGoal(this.props.params.id)
      this.toggleConfirmationModal()
      this.props.router.goBack()
    }
  
    canEdit () {
      return this.props.auth.uid === this.props.goal.uid
    }
  
    render () {
      const { goal, goalActions, intl: { formatMessage } } = this.props
  
      if (goal === undefined) { return <Loading /> }
  
      return (
        <div className="mb-3">
          <PageHeading>{ goal.text }</PageHeading>
  
          { this.canEdit() && <div className="text-center">
            <ButtonGroup className="mt-2">
              <Button onClick={ this.toggle.bind(this, null) }>{ formatMessage(TH.addAction) }</Button>
              <Button onClick={ this.toggleGoalModal.bind(this) }>{ formatMessage(content.editGoal) }</Button>
            </ButtonGroup>
          </div> }
  
          { goalActions &&
            <div className="mt-3">
              <p className="mb-0"><b>{ formatMessage(TH.actionsList) }</b></p>
              <SimpleList
                items={ goalActions }
                sort={ this.state.actionsSort }
                sortOrder={ this.state.sortOrder }
                filters={ this.state.actionsFilters }
                actions={ this.state.actions }
                containerClasses="mt-1 mb-3"
                limitItems
              />
            </div>
          }
  
          { goalActions &&
            <div className="mt-3">
              <p className="mb-0"><b>{ formatMessage(content.recentlyCompletedActions) }</b></p>
              <RecentActionsList items={ goalActions } containerClasses="mt-1 mb-3" />
            </div>
          }
  
          { goal.partner && typeof goal.partner !== 'string' && <GoalPartners title={ formatMessage(TH.partner) } partner={ goal.partner } /> }
  
          { goal.outcome && <Feature title={ formatMessage(content.desiredOutcome) } content={ goal.outcome } /> }
          { goal.evidenceProcedure && <Feature title={ formatMessage(content.evidenceProcedure) } content={ goal.evidenceProcedure } /> }
          { goal.deadline && <Feature title={ formatMessage(content.deadline) } content={ goal.deadline } /> }
          { goal.reasons && <Feature title={ formatMessage(content.reasons) } content={ goal.reasons } /> }
  
          <BackButton action={ this.props.router.goBack } />
  
  
          <hr />
  
          <DateTime text={ formatMessage(content.createdOn) } time={ goal.cdate } />
          { goal.primarySet && <DateTime text={ formatMessage(content.primaryOn) } time={ goal.primarySet } /> }
          <p className="mt-4 text-danger pointer" onClick={ this.toggleConfirmationModal.bind(this) }><small>{ formatMessage(content.deleteGoal) }</small></p>
  
          <GoalModal
            isOpen={ this.state.goalModal }
            toggle={ this.toggleGoalModal.bind(this) }
            onSubmit={ this.goalModalSubmit.bind(this) }
            fields={ this.state.goalFields }
            initialValues={ goal }
          />
  
          <ActionModal
            isOpen={ this.state.modal }
            toggle={ this.toggle.bind(this) }
            danger={ this.actionDelete.bind(this) }
            onSubmit={ this.actionModalSubmit.bind(this) }
            initialValues={ this.state.item }
            item={ this.state.item }
          />
  
  
          <ConfirmationModal isOpen={ this.state.confirmationModal } danger={ this.deleteGoal.bind(this) } toggle={ this.toggleConfirmationModal.bind(this) }>
            { formatMessage(TH.goalDeleteConfirmation) }
          </ConfirmationModal>
        </div>
      )
    }
  }
  
  export default injectIntl(GoalContainer)
  
        // dndActions: {
        //   'endDrag': this.endDragAction.bind(this)
        // }
  
    // reducePriority(target) {
    //   return (target.priority > 1) ? target.priority - 1 : 1
    // }
  
    // increasePriority(target) {
    //   return (target.priority < 9) ? target.priority + 1 : 9
    // }
  
    // endDragAction (draggedItem, dropTarget) {
    //   if (dropTarget === null || draggedItem.key === dropTarget.key) { return }
    //   let increase = ((dropTarget.priority > draggedItem.priority) || (dropTarget.priority === draggedItem.priority && dropTarget.cdate < draggedItem.cdate))
    //   let update = { priority: (increase) ? this.increasePriority(dropTarget) : this.reducePriority(dropTarget) }
  
    //   updateAction(this.props.params.id, draggedItem.key, update)
    // }