import React, { PropsWithChildren, useMemo, useState } from 'react'
import {
  HuiContent,
  defaultToastLayout,
  HuiContextParams,
  UpdateToastsFunction,
  UpdateToastsIDFunction,
  UpdateToastsLayoutFunction
} from '../utils/use-hui-context'
import ThemeProvider from './theme-provider'
import useCurrentState from '../utils/use-current-state'
import ToastContainer from '../use-toasts/toast-container'
import { HuiThemes } from '../themes/presets'

export type HuiProviderProps = {
  themes?: Array<HuiThemes>
  themeType?: string | 'dark' | 'light'
}

const HuiProvider: React.FC<PropsWithChildren<HuiProviderProps>> = ({
  themes,
  themeType,
  children
}) => {
  const [lastUpdateToastId, setLastUpdateToastId] =
    useState<HuiContextParams['lastUpdateToastId']>(null)
  const [toasts, setToasts, toastsRef] = useCurrentState<HuiContextParams['toasts']>([])
  const [toastLayout, setToastLayout, toastLayoutRef] =
    useCurrentState<HuiContextParams['toastLayout']>(defaultToastLayout)
  const updateToasts: UpdateToastsFunction = (fn) => {
    const nextToasts = fn(toastsRef.current)
    setToasts(nextToasts)
  }
  const updateToastLayout: UpdateToastsLayoutFunction = (fn) => {
    const nextLayout = fn(toastLayoutRef.current)
    setToastLayout(nextLayout)
  }
  const updateLastToastId: UpdateToastsIDFunction = (fn) => {
    setLastUpdateToastId(fn())
  }

  const initialValue = useMemo<HuiContextParams>(
    () => ({
      toasts,
      toastLayout,
      updateToasts,
      lastUpdateToastId,
      updateToastLayout,
      updateLastToastId
    }),
    [toasts, toastLayout, lastUpdateToastId]
  )

  return (
    <HuiContent.Provider value={initialValue}>
      <ThemeProvider themes={themes} themeType={themeType}>
        {children}
        <ToastContainer />
      </ThemeProvider>
    </HuiContent.Provider>
  )
}

export default HuiProvider
