import { useMemo, useCallback, createContext, useState } from 'react'
import * as Auth from 'aws-amplify/auth'

const AuthContext = createContext(null)

export function useAuth() {
  return useContext(AuthContext)
}

export function AuthProvider({ children }) {
  const [authUser, setAuthUser] = useState(null)

  const currentUser = useCallback(async () => {
    try {
      const currentUser = await Auth.fetchUserAttributes()

      setAuthUser(currentUser)
      return currentUser
    } catch {
      setAuthUser(null)
    }
  }, [])

  const signIn = useCallback(async ({ username, password }) => {
    const signInOut = await Auth.signIn({
      username,
      password,
      options: {
        clientMetadata: {},
      },
    })

    if (signInOut?.isSignedIn) {
      setAuthUser(await Auth.fetchUserAttributes())
    }

    return signInOut
  }, [])

  const ctxValue = useMemo(
    () => ({
      authUser,
      signIn,
      currentUser,
    }),
    [authUser]
  )

  return <AuthContext.Provider value={ctxValue}>{children}</AuthContext.Provider>
}
