import React, {useState} from 'react'
import PropTypes from 'prop-types'
import {intlShape} from 'react-intl'
import EntityDetailApp from 'tocco-entity-detail/src/main'
import {Prompt} from 'react-router'
import styled from 'styled-components'

const EntityDetailAppWrapper = styled.div`
  margin: 1rem 0 1rem 1rem;
`

const CreateView = props => {
  const [touched, setTouched] = useState(false)

  const mode = 'create'

  if (!props.currentViewInfo) {
    return null
  }

  const {model, reverseRelation, key} = props.currentViewInfo
  const entityName = model.name

  const defaultValues = [
    ...((reverseRelation && key) ? [{id: reverseRelation, value: key}] : [])
  ]

  const handleEntityCreated = ({id}) => {
    setTouched(false)
    props.history.push(props.match.url.replace(/create$/, id))
  }

  const handleToucheChanged = ({touched}) => {
    setTouched(touched)
  }

  const msg = id => props.intl.formatMessage({id})

  return (
    <EntityDetailAppWrapper>
      <Prompt
        when={touched}
        message={msg('client.entity-browser.detail.confirmTouchedFormLeave')}
      />
      <EntityDetailApp
        entityName={entityName}
        formName={entityName}
        mode={mode}
        defaultValues={defaultValues}
        emitAction={action => {
          props.dispatchEmittedAction(action)
        }}
        onEntityCreated={handleEntityCreated}
        onTouchedChange={handleToucheChanged}
      />
    </EntityDetailAppWrapper>
  )
}

CreateView.propTypes = {
  intl: intlShape,
  match: PropTypes.object,
  history: PropTypes.object,
  currentViewInfo: PropTypes.object,
  dispatchEmittedAction: PropTypes.func.isRequired
}

export default CreateView

@@ -66,16 +66,46 @@
 -types'%0A
+import _get from 'lodash/get'%0A
 import %7B
@@ -594,16 +594,103 @@
 l.name%0A%0A
+  const isMultiReverseRelation = _get(model, %60paths.$%7BreverseRelation%7D.multi%60, false)%0A%0A
   const 
@@ -739,16 +739,22 @@
  && key)
+%0A     
  ? %5B%7Bid:
@@ -782,18 +782,62 @@
 ue: 
-key%7D%5D : %5B%5D
+isMultiReverseRelation ? %5Bkey%5D : key%7D%5D%0A      : %5B%5D%0A    
 )%0A  

check if reverse-relation is multi