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 RootModal from './RootModal'

const isDevelopment = process.env.NODE_ENV == 'development'

export const campxTenantKey = isDevelopment
  ? Cookies.get('campx_tenant')
  : window.location.hostname.split('.')[0]
export const urlTenantKey = isDevelopment
  ? Cookies.get('campx_tenant')
  : window.location.hostname.split('.')[0]
export const instituitionKey =
  window.location.pathname.split('/')[1] != ''
    ? window.location.pathname.split('/')[1]
    : Cookies.get('campx_institution')

export default function Providers({ children }: { children: ReactNode }) {
  var baseName = '/'
  var tenantCode
  var institutionCode =
    window.location.pathname.split('/')[1] != ''
      ? window.location.pathname.split('/')[1]
      : Cookies.get('campx_institution')

  if (isDevelopment) {
    tenantCode = Cookies.get('campx_tenant')
    if (
      tenantCode &&
      institutionCode &&
      window.location.pathname !== '/auth/login'
    ) {
      baseName = `/${institutionCode}`
    }
  } else {
    tenantCode = window.location.hostname.split('.')[0]
    if (institutionCode && window.location.pathname !== '/auth/login') {
      baseName = `/${institutionCode}`
    }
  }

  useEffect(() => {
    if (location.pathname === '/' && institutionCode && tenantCode) {
      window.location.replace(window.location.origin + `/${institutionCode}`)
    }
  }, [])
  return (
    <BrowserRouter basename={baseName}>
      <QueryClientProvider>
        <MuiThemeProvider>
          <ConfirmContextProvider>
            <DialogProvider>
              <ErrorModalProvider>{children}</ErrorModalProvider>
              <GlobalNetworkLoadingIndicator />
              <RootModal />
              <ToastContainer />
            </DialogProvider>
          </ConfirmContextProvider>
        </MuiThemeProvider>
      </QueryClientProvider>
    </BrowserRouter>
  )
}
