import React, { useState } from 'react'
import { observer } from 'mobx-react-lite'
import { FormScreen } from './FormScreen'
import type { NativeStackScreenProps } from '@react-navigation/native-stack'
import { useAppStore } from './store'
import { createEntityTable, useEntityModel } from './EntityTable'

type Props = NativeStackScreenProps<any>

export const EntityAssocScreen: React.FC<Props> = observer((props) => {
  const appStore = useAppStore()
  const params = appStore.getRouteConfig(props.route)
  const model = params.entityModel
  const assocField = params.assocField
  const setAssocFieldValue = params.setAssocFieldValue
  const {} = useEntityModel(model)

  const [Table] = useState(() => {
    // Associate the selected organization with the loadedItem in params.parentAssocEntityModel
    model.config.entityListScreenConfig.onSelection = (_event: any, item: any) => {
      setAssocFieldValue(assocField, item)
      props.navigation.goBack()
    }
    // Don't show new button
    model.config.entityListScreenConfig.onNewPress = null
    return createEntityTable<any>()
  })

  return (
    <FormScreen>
      <Table model={model} />
    </FormScreen>
  )
})
