import React from 'react'
import { LinkRedirectInfo } from 'types/linkRedirects'

export interface LinkRedirectContextType {
  linkRedirect: LinkRedirectInfo
  setLinkRedirect: React.Dispatch<React.SetStateAction<LinkRedirectInfo>>
}

const LinkRedirectContext = React.createContext<
  LinkRedirectContextType | undefined
>(undefined)

export const LinkRedirectProvider: React.FC = ({ children }) => {
  const [linkRedirect, setLinkRedirect] = React.useState<LinkRedirectInfo>({
    link: '',
    scheduledTimezone: '',
    scheduledStartTimestamp: 0,
    scheduledEndTimestamp: 0,
    isEnabled: false
  })

  return (
    <LinkRedirectContext.Provider value={{ linkRedirect, setLinkRedirect }}>
      {children}
    </LinkRedirectContext.Provider>
  )
}

export const useLinkRedirect = (): LinkRedirectContextType => {
  const context = React.useContext(LinkRedirectContext)
  if (context === undefined) {
    throw new Error(
      'useLinkRedirect must be used within a LinkRedirectProvider'
    )
  }
  return context
}
