import React, { useMemo } 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 } from './EntityTable'
import type { EntityModelType } from './EntityModel'

type Props = NativeStackScreenProps<any, any>

const EntityM2MAssocScreen: React.FC<Props> = observer((props) => {
  const appStore = useAppStore()
  const params = appStore.getRouteConfig(props.route)
  const relation = params.relation
  const assocModel = relation.assocModel as EntityModelType
  const fieldModel = relation.fieldModel as EntityModelType

  const TheTable = useMemo(() => {
    // Associate the selected organization with the loadedItem in params.parentAssocEntityModel
    assocModel.config.entityListScreenConfig.onSelection = (_event, item: any | any[]) => {
      // We may have single or multiple selections. At the end we need to pass an array of ID-s to associate
      const itemIds = Array.isArray(item) ? item.map((i) => i.id) : [item.id]
      let mut = params.rootEntityModel.associate(relation, itemIds)
      mut.then(
        (/*result*/) => {
          assocModel.reloadList()
          fieldModel.reloadList()
          props.navigation.goBack()
        },
        (/*error*/) => {}
      )
    }
    // Don't show new button
    assocModel.config.entityListScreenConfig.onNewPress = null
    return createEntityTable({ model: assocModel })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [assocModel])

  return (
    <FormScreen>
      <TheTable model={assocModel} />
    </FormScreen>
  )
})

export default EntityM2MAssocScreen
