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 { CssBaseline, Theme, ThemeProvider } from '@mui/material'
import { CreateTheme } from '../theme/theme'
import { getThemeType, setThemeType } from '../theme/themeType'
import { getWhitelabel } from 'services/whiteLabel'

function App() {
  const [token, setToken] = useState<string | undefined>(undefined)
  const [palette, setPalette] = useState<Theme>(CreateTheme(getThemeType()));

  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"
  })

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

  let client_id = import.meta.env.VITE_AUTH0_DEV_CLIENT_ID;

  const toggleTheme = () => {
    if (getThemeType() === "light") {
      setPalette(CreateTheme("dark"));
      setThemeType("dark");
    } else {
      setPalette(CreateTheme("light"));
      setThemeType("light");
    }
  };

  return (
    <Auth0Provider
      domain={or(url, "")}
      clientId={or(client_id, "")}
      authorizationParams={{
        audience: or(audience, ""),
        redirect_uri: window.location.origin + "/callback"
      }}
      useRefreshTokens={true}
      cacheLocation='localstorage'
    >
      <ThemeProvider theme={palette}>
        <CssBaseline />
        <AuthWrapper setToken={setToken}>
          { token ? 
            <HTTPProvider token={token}>
              <UserWrapper toggleTheme={toggleTheme}/>
            </HTTPProvider>
          :
            <LoadingScreen
              message='Loading user profile'
            />
          }
        </AuthWrapper>
      </ThemeProvider>
    </Auth0Provider>
  )
}

export default App
