import { BrowserRouter } from 'react-router-dom'
import ConfirmContextProvider from '../components/PopupConfirm/ConfirmContextProvider'
import MuiThemeProvider from '../theme/MuiThemeProvider'
import QueryClientProvider from './QueryClientProvider'

import Cookies from 'js-cookie'
import { ReactNode, useEffect } from 'react'
import { ToastContainer } from '../components'
import DialogProvider from '../components/DrawerWrapper/DrawerWrapper'
import GlobalNetworkLoadingIndicator from '../components/ErrorBoundary/GlobalNetworkLoadingIndicator'
import ErrorModalProvider from '../components/ErrorModalWrapper/ErrorModalWrapper'
import { isDevelopment } from '../constants'
import RootModal from './RootModal'

export const campxTenantKey = Cookies.get('campx_tenant')
export const urlTenantKey = window.location.pathname.split('/')[1]
export const instituitionKey = window.location.pathname.split('/')[2]

export default function Providers({ children }: { children: ReactNode }) {
  const localInstituitionKey = localStorage.getItem('institution_key')

  const getInstituitionKey = () => {
    if (instituitionKey) {
      return instituitionKey
    } else {
      if (!urlTenantKey) return null
      if (localInstituitionKey) {
        return localInstituitionKey
      } else {
        return null
      }
    }
  }

  useEffect(() => {
    if (!urlTenantKey) {
      if (isDevelopment) {
        window.location.replace(window.location.origin + `/aupulse`)
      }
      if (campxTenantKey)
        window.location.replace(window.location.origin + `/${campxTenantKey}`)
    } else {
      if (!instituitionKey) {
        if (localInstituitionKey) {
          window.location.replace(
            window.location.origin + `/${urlTenantKey}/${localInstituitionKey}`,
          )
        }
      }
    }
  }, [])

  const baseName = getInstituitionKey()
    ? `${urlTenantKey}/${getInstituitionKey()}`
    : urlTenantKey

  return (
    <BrowserRouter basename={baseName}>
      <QueryClientProvider>
        <MuiThemeProvider>
          <ConfirmContextProvider>
            <DialogProvider>
              <ErrorModalProvider>{children}</ErrorModalProvider>
              <GlobalNetworkLoadingIndicator />
              <RootModal />
              <ToastContainer />
            </DialogProvider>
          </ConfirmContextProvider>
        </MuiThemeProvider>
      </QueryClientProvider>
    </BrowserRouter>
  )
}
