import type { CommonProps } from '@/@types/common'
import ConfigProvider from '@/components/ui/ConfigProvider'
import { themeConfig } from '@/configs/theme.config'
import { useStoreActions, useStoreState } from '@/store'
import useDarkMode from '@/utils/hooks/useDarkmode'
import useNotification from '@/utils/hooks/useNotification'
import { useSetting } from '@/utils/hooks/useSetting'
import useTabFocus from '@/utils/hooks/useTabFocus'
import { useEffect } from 'react'
import { Helmet } from 'react-helmet'

let didInit = false

const Theme = (props: CommonProps) => {
  // ABP App Config'i uygulama acilirken al
  const { getConfig } = useStoreActions((a) => a.abpConfig)

  useEffect(() => {
    if (!didInit) {
      didInit = true
      getConfig(false)
    }
  }, [])

  function getThemeStyle() {
    const mode = theme.mode
    const style = setting('App.SiteManagement.Theme.Style')

    return style?.replace(mode === 'dark' ? 'light' : 'dark', mode)
  }

  const { setting } = useSetting()

  const theme = useStoreState((state) => state.theme)
  const locale = useStoreState(
    (state) => state.abpConfig.config?.localization.currentCulture.cultureName,
  )
  useDarkMode()
  useTabFocus()
  useNotification()

  const currentTheme = {
    ...themeConfig,
    ...theme,
    ...{ locale },
  }

  return (
    <>
      {setting('App.SiteManagement.Theme.Style') && (
        <Helmet key="Devexpress stylesheet Helmet">
          <link
            key="Devexpress stylesheet Helmet link"
            rel="stylesheet"
            href={`/css/${getThemeStyle()}.css`}
          />
        </Helmet>
      )}
      <ConfigProvider value={currentTheme}>{props.children}</ConfigProvider>
    </>
  )
}

export default Theme
