import { Auth0Provider } from '@auth0/auth0-react'
import { or } from '../utils/types'
import AuthWrapper from '../providers/auth'
import HTTPProvider from 'providers/http'
import { useState } from 'react'
import LoadingScreen from './LoadingScreen'
import UserWrapper from './UserWrapper'
import { getWhitelabel } from 'services/whiteLabel'
import { AppThemeProvider } from 'theme/AppThemeProvider'

function App() {
  const [token, setToken] = useState<string | undefined>(undefined)

  const whiteLabel = getWhitelabel()
  const manifestPath = "/" + whiteLabel.name.replace(/\s/g, "") + "/manifest.json"
  const manifestDocument = document.getElementById('manifest-link') as HTMLLinkElement
  fetch(manifestPath).then(response => {
    if (response.ok && manifestDocument) {
      manifestDocument.href = manifestPath;
    } else {
      manifestDocument.href = "BrandXTechnologies/manifest.json"
    }
  }).catch(() => {
    manifestDocument.href = "BrandXTechnologies/manifest.json"
  })

  // Set favicon
  const faviconDocument = document.getElementById("favicon-link") as HTMLLinkElement;
  const faviconPath = `/${whiteLabel.name.replace(/\s/g, "")}/favicon.ico`;
  fetch(faviconPath).then(response => {
    if (response.ok && faviconDocument) {
      faviconDocument.href = faviconPath;
    } else {
      faviconDocument.href = "/BrandXTechnologies/favicon.ico"
    }
  }).catch(() => {
    faviconDocument.href = "BrandXTechnologies/favicon.ico"
  })

  // Set title
  const titleElement = document.getElementById("title-id") as HTMLElement;
  if (titleElement) titleElement.textContent = whiteLabel.name;


  let domain: string | undefined = import.meta.env.VITE_AUTH0_CLIENT_DOMAIN;
  let audience: string | undefined = import.meta.env.VITE_AUTH0_AUDIENCE;

  let client_id = whiteLabel.auth0ClientId
  if (!client_id) client_id = import.meta.env.VITE_AUTH0_CLIENT_ID;

  const skipCallbacks = [
    "/johndeere",
    "/cnhi",
    "/libracart"
  ]

  return (
    <AppThemeProvider>
      <Auth0Provider
        domain={or(domain, "")}
        clientId={or(client_id, "")}
        authorizationParams={{
          audience: or(audience, ""),
          redirect_uri: window.location.origin + "/callback"
        }}
        skipRedirectCallback={skipCallbacks.includes(window.location.pathname)}
        useRefreshTokens={true}
        cacheLocation='localstorage'
      >
        {/* <CssBaseline /> */}
        <AuthWrapper setToken={setToken}>
          { token ? 
            <HTTPProvider token={token}>
              <UserWrapper token={token} />
            </HTTPProvider>
          :
            <LoadingScreen
              message='Loading user profile'
            />
          }
        </AuthWrapper>
      </Auth0Provider>
    </AppThemeProvider>
  )
}

export default App
