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

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

export type NewsContextProperties = {
  isLoginOpen: boolean
  setIsLoginOpen: Dispatch<SetStateAction<boolean>>
  isRegisterOpen: boolean
  setIsRegisterOpen: Dispatch<SetStateAction<boolean>>
  isForgetOpen: boolean
  setForgetOpen: Dispatch<SetStateAction<boolean>>
  isSuccessOpen: ModalProperties['isOpen']
  setIsSuccessOpen: Dispatch<
    SetStateAction<ModalProperties['isOpen'] | undefined>
  >
  isInitSubscribeOpen: boolean
  setIsInitSubscribeOpen: 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, setForgetOpen] = useState(false)
  const [isSuccessOpen, setIsSuccessOpen] =
    useState<ModalProperties['isOpen']>()
  const [isInitSubscribeOpen, setIsInitSubscribeOpen] = useState(false)

  return (
    <NewsContext.Provider
      value={{
        isLoginOpen,
        setIsLoginOpen,
        isRegisterOpen,
        setIsRegisterOpen,
        isForgetOpen,
        setForgetOpen,
        isSuccessOpen,
        setIsSuccessOpen,
        isInitSubscribeOpen,
        setIsInitSubscribeOpen,
      }}
    >
      {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
}
