import React, { useMemo } from 'react'
import type { NativeStackScreenProps } from '@react-navigation/native-stack'
import { createEntityTable } from './EntityTable'
import { observer } from 'mobx-react-lite'
import { FormScreen } from './FormScreen'
import { useAppStore } from './store'
import { useFocusEffect } from '@react-navigation/native'
import type { EntityModelType } from './EntityModel'
// import { getType } from 'mobx-state-tree'

type Props = NativeStackScreenProps<any, any>

const EntityListScreen: React.FC<Props> = observer((props) => {
  const appStore = useAppStore()
  // Get rootEntityModel from either the props.route.params or from the routeConfigs. Initial
  // EntityListScreens get their rootEntityModel as initialParams available here in props.route.params
  const { rootEntityModel }: { rootEntityModel: EntityModelType } = appStore.getRouteConfig(props.route)

  // Memoize, so that createEntityTable() is invoked only when necessary (ie. only once)
  const TheTable = useMemo(() => {
    // const modelName = getType(rootEntityModel).name
    rootEntityModel.config.entityListScreenConfig.onSelection = (_event, item: any) => {
      rootEntityModel.setSelectedId(item.id)
      appStore.navigate(props.navigation as any, rootEntityModel.config.detailsScreenRouteNameVal(), {
        parentRoute: props.route.name,
        rootEntityModel: rootEntityModel,
        title: rootEntityModel.config.detailsScreenRouteTitleVal(item),
        //screenModel: appStore.serviceAccountScreens.serviceAccountDetailsScreen,
      })
    }

    rootEntityModel.config.entityListScreenConfig.onNewPress = (_event) => {
      rootEntityModel.setEditId(null)
      appStore.navigate(props.navigation as any, rootEntityModel.config.createFormScreenRouteNameVal(), {
        parentRoute: props.route.name,
        rootEntityModel: rootEntityModel,
        // Editing own values. When we edit related fields, it will be the entityModel of the
        // associated type
        entityModel: rootEntityModel,
        title: rootEntityModel.config.createFormScreenRouteTitleVal(),
      })
    }

    return createEntityTable({ model: rootEntityModel })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rootEntityModel])

  // Redefine onDeletePress on focus, which is also used by CreateEditServiceAccountScreen.tsx
  useFocusEffect(
    React.useCallback(() => {
      rootEntityModel.config.entityListScreenConfig.onDeletePress = (_event, item, _config) => {
        rootEntityModel.delete([item]).then(() => {
          rootEntityModel.reloadList()
        })
      }
      // Uncomment this to reload screen whenever navigating to ListScreen
      //rootEntityModel.reloadList()
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
  )

  return (
    <FormScreen>
      <TheTable />
    </FormScreen>
  )
})

export default EntityListScreen
