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

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 = window.location.hostname.includes('localhost')

export const campxTenantKey = window.location.hostname.split('.')[0]
export const urlTenantKey = window.location.hostname.split('.')[0]
export const instituitionKey = window.location.pathname.split('/')[1]

export default function Providers({ children }: { children: ReactNode }) {
  var baseName = '/'
  var tenantCode = window.location.hostname.split('.')[0]
  var institutionCode = window.location.pathname.split('/')[1]

  if (institutionCode && window.location.pathname !== '/auth/login') {
    baseName = `/${institutionCode}`
  }

  useEffect(() => {
    if (window.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>
  )
}
