import React, {
  createContext,
  FunctionComponent,
  useEffect,
  useState,
  memo,
} from 'react'

type NotificationBarProps = Readonly<{
  duration?: number | null
}>

type NotificationProps = Readonly<{
  duration: number | null
  notification: string
  setNotification: any
}>

type NotificationBarProviderProps = Readonly<{
  children: any
}>

type State = string | null

type Context = {
  notification: string | null
  setNotification: (notification: any) => void
}

const { Provider, Consumer } = createContext<Context>({
  notification: null,
  setNotification: (notification) => notification,
})

const NotificationBase: FunctionComponent<NotificationProps> = ({
  duration = null,
  notification,
  setNotification,
}) => {
  const dismissNotification = () => setNotification(null)
  useEffect(() => {
    if (!duration) return
    const timer = setTimeout(dismissNotification, duration)
    return () => clearTimeout(timer)
  })
  return notification ? (
    <div className="ui-notification-bar-wrapper ui-bg__orange--soft-transparency">
      <div className="ui-grid-container">
        <div className="ui-grid">
          <div className="ui-grid-col ui-color--charcoal-lightest">
            {notification}
          </div>
          <div className="ui-grid-col ui-text--right">
            <button
              className="ui-btn ui-btn__link"
              onClick={() => dismissNotification()}
            >
              <span className="ui-icon--close ui-btn__link ui-scale--1 ui-color--charcoal-lightest" />
            </button>
          </div>
        </div>
      </div>
    </div>
  ) : null
}

export const Notification = memo(NotificationBase)

export const NotificationBar: FunctionComponent<NotificationBarProps> = ({
  duration = 2000,
}) => {
  return (
    <NotificationBarConsumer>
      {({ notification, setNotification }) =>
        notification && setNotification ? (
          <Notification
            duration={duration}
            notification={notification}
            setNotification={setNotification}
          />
        ) : null
      }
    </NotificationBarConsumer>
  )
}

const NotificationBarProviderBase: FunctionComponent<
  NotificationBarProviderProps
> = ({ children }) => {
  const [notification, setNotification] = useState<State>(null)
  return (
    <Provider value={{ notification, setNotification }}>{children}</Provider>
  )
}

export const NotificationBarProvider = memo(NotificationBarProviderBase)
export const NotificationBarConsumer = Consumer
