import React, {
  FC,
  useEffect,
  useState,
  createContext,
  useContext
} from 'react'

import { userServiceCurrentProfile } from 'apiClient/services/core-server'
import type { V1PrincipalProfile } from 'apiClient/services/core-server/interface'
import { PageLoader } from 'components/Loader'

interface IState {
  profile: V1PrincipalProfile
  fetch: () => void
}

const UserProfileContext = createContext<IState | undefined>({
  profile: {},
  fetch: () => {}
})

const useProfileContext = () => {
  const context = useContext(UserProfileContext)
  if (context === undefined) {
    throw new Error('useProfileContext must be used within a ListProvider')
  }
  return context
}

export const UserProfileContextProvider: FC<
  React.PropsWithChildren<unknown>
> = ({ children }) => {
  const [loading, setLoading] = useState(true)
  const [profile, setProfile] = useState<V1PrincipalProfile>({})

  async function fetch() {
    const data = (
      await userServiceCurrentProfile({
        isShowMessage: true
      })
    ).data
    setProfile(data)
  }

  useEffect(() => {
    async function init() {
      await fetch()
      setLoading(false)
    }

    init()
  }, [])

  return (
    <UserProfileContext.Provider value={{ profile, fetch }}>
      {loading ? <PageLoader tip="Please wait..." /> : children}
    </UserProfileContext.Provider>
  )
}

export default useProfileContext
