import {
  createContext,
  useState,
  useContext,
  type PropsWithChildren,
  type Dispatch,
  type SetStateAction,
} from 'react'

import type { ModalProperties } from '~/components/popup/success-modal'

type NewsContextProperties = {
  isLoginOpen: boolean
  setIsLoginOpen: Dispatch<SetStateAction<boolean>>
  isRegisterOpen: boolean
  setIsRegisterOpen: Dispatch<SetStateAction<boolean>>
  isForgetOpen: boolean
  setIsForgetOpen: Dispatch<SetStateAction<boolean>>
  isSuccessOpen: ModalProperties['isOpen']
  setIsSuccessOpen: Dispatch<
    SetStateAction<ModalProperties['isOpen'] | undefined>
  >
  isSubscribeOpen: boolean
  setIsSubscribeOpen: Dispatch<SetStateAction<boolean>>
}

const NewsContext = createContext<NewsContextProperties | undefined>(undefined)

export const NewsProvider = ({ children }: PropsWithChildren) => {
  const [isLoginOpen, setIsLoginOpen] = useState(false)
  const [isRegisterOpen, setIsRegisterOpen] = useState(false)
  const [isForgetOpen, setIsForgetOpen] = useState(false)
  const [isSuccessOpen, setIsSuccessOpen] =
    useState<ModalProperties['isOpen']>()
  const [isSubscribeOpen, setIsSubscribeOpen] = useState(false)

  return (
    <NewsContext.Provider
      value={{
        isLoginOpen,
        setIsLoginOpen,
        isRegisterOpen,
        setIsRegisterOpen,
        isForgetOpen,
        setIsForgetOpen,
        isSuccessOpen,
        setIsSuccessOpen,
        isSubscribeOpen,
        setIsSubscribeOpen,
      }}
    >
      {children}
    </NewsContext.Provider>
  )
}

export const useNewsContext = (): NewsContextProperties => {
  const context = useContext(NewsContext)
  if (!context) {
    throw new Error('useNewsContext must be used within a NewsProvider')
  }
  return context
}
