import { createContext, useMemo, useState } from 'react'

import { createUseContext } from '@lib/react'

type HeaderProviderProps = {
  title?: string
  children: React.ReactNode
}

type HeaderProviderState = {
  title?: string
  setTitle: (title?: string) => void
}

const initialState: HeaderProviderState = {
  setTitle: () => null,
}

const HeaderContext = createContext<HeaderProviderState>(initialState)

export function HeaderProvider({ children, title, ...props }: Readonly<HeaderProviderProps>) {
  const [headerTitle, setHeaderTitle] = useState(title)

  const value = useMemo(
    () => ({
      title: headerTitle,
      setTitle: (title?: string) => {
        setHeaderTitle(title)
      },
    }),
    [headerTitle],
  )

  return (
    <HeaderContext.Provider {...props} value={value}>
      {children}
    </HeaderContext.Provider>
  )
}

export const useHeader = createUseContext(HeaderContext, 'HeaderProviderContext')
