import { Suspense, useContext, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { Flex, Spin } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import PropTypes from 'prop-types'
import { getModelByName } from '../../../database/ObjectModels'
import { getObjectIdFromSearch } from '../../../utils/modelActions'
import { useActions } from '../context/ActionsContext'
import { AuthContext } from '../context/AuthContext'

const ModelPage = ({ modelName, pageName }) => {
  const model = getModelByName(modelName)
  const page = model.pages?.find((p) => p.name === pageName)
  const location = useLocation()
  const { setCurrentObject, setCurrentObjectType } = useActions()
  const { userProfile } = useContext(AuthContext)
  const objectId = getObjectIdFromSearch(modelName, location.search)

  useEffect(() => {
    setCurrentObjectType(modelName)
    if (objectId) {
      setCurrentObject({ _id: objectId, _user: userProfile })
    }
    return () => {
      setCurrentObject(null)
      setCurrentObjectType(null)
    }
  }, [modelName, objectId, setCurrentObject, setCurrentObjectType, userProfile])

  if (!page?.content) {
    return null
  }

  return (
    <Suspense
      fallback={
        <Flex
          justify='center'
          align='center'
          style={{ width: '100%', height: '100%' }}
        >
          <Spin indicator={<LoadingOutlined spin />} />
        </Flex>
      }
    >
      {page.content()}
    </Suspense>
  )
}

ModelPage.propTypes = {
  modelName: PropTypes.string.isRequired,
  pageName: PropTypes.string.isRequired
}

export default ModelPage
