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

const AuthContext = createContext(null)

export function useAuth() {
  const ctx = useContext(AuthContext)

  if (!ctx) {
    throw new Error('useAuth must be used within an AuthProvider')
  }

  return ctx
}

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

  useEffect(() => {
    Auth.fetchUserAttributes()
      .then((user) => {
        setAuthUser(user)
      })
      .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 signOut = useCallback(async () => {
    try {
      return await Auth.signOut()
    } catch {}
  }, [])

  const authContext = useMemo(
    () => ({
      authUser,
      signIn,
      signOut,
    }),
    [authUser, signIn, signOut],
  )

  return (
    <AuthContext.Provider value={authContext}>{children}</AuthContext.Provider>
  )
}
