'use client'

import { User } from '@/payload-types'
import { createContext, ReactNode, useContext, useState } from 'react'

type GlobalProps = {
  user?: User
}

type GlobalState = {
  setUser: (users?: User) => void
} & GlobalProps

const defaultState = {
  user: undefined,
  setUser: (user?: User) => {},
}

const GlobalContext = createContext<GlobalState>(defaultState)

type Props = { children: ReactNode; globalProps: GlobalProps }
export function GlobalProvider({ children, globalProps }: Props) {
  const [user, setUser] = useState(globalProps.user)

  const value = {
    user,
    setUser,
  }

  return <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
}

export function useGlobal() {
  return useContext(GlobalContext)
}
