import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom/client';
import './index.css';
import './styles/powerbi.css';
import reportWebVitals from './reportWebVitals';
import { ThemeProvider } from '@mui/system';
import { BrowserRouter } from 'react-router-dom';
import { store } from './api';
import { App, theme } from './app';
import './fontawesome';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import OktaAuth, { toRelativeUrl } from '@okta/okta-auth-js';
import { Security } from '@okta/okta-react';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

const oktaAuth = new OktaAuth({
  issuer: import.meta.env.VITE_OKTA_ISSUER
    ? import.meta.env.VITE_OKTA_ISSUER
    : 'https://oneid.oneonctest.net/oauth2/default',
  clientId: import.meta.env.VITE_OKTA_CLIENTID
    ? import.meta.env.VITE_OKTA_CLIENTID
    : '0oa296mj3sk6ump4r0h8',
  redirectUri: window.location.origin + '/login/callback',
  pkce: true,
  scopes: ['openid', 'profile', 'email', 'offline_access'],
  tokenManager: {
    autoRenew: true,
    autoRemove: true,
  },
});

const triggerLogin = async () => {
  await oktaAuth.signInWithRedirect();
};

const customAuthHandler = async () => {
  const previousAuthState = oktaAuth.authStateManager.getPreviousAuthState();

  if (!previousAuthState || !previousAuthState.isAuthenticated) {
    await triggerLogin();
  }
};

const restoreOriginalUri = async (_oktaAuth: any, originalUri: any) => {
  window.location.replace(
    toRelativeUrl(originalUri || '/', window.location.origin)
  );
};

root.render(
  // <React.StrictMode>
  <LocalizationProvider dateAdapter={AdapterDayjs}>
    <Provider store={store}>
      <ThemeProvider theme={theme}>
        <BrowserRouter>
          <Security
            oktaAuth={oktaAuth}
            onAuthRequired={customAuthHandler}
            restoreOriginalUri={restoreOriginalUri}
          >
            <App />
          </Security>
        </BrowserRouter>
      </ThemeProvider>
    </Provider>
  </LocalizationProvider>
  // </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
