import { useCallback, useEffect, useRef, useState } from 'react'
import reactLogo from '../assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { useUserAPI } from '../providers/pond/userAPI'
import { useAuth0 } from '@auth0/auth0-react'
import { or } from '../utils/types'
import LoadingScreen from './LoadingScreen'
import { pond } from "protobuf-ts/pond";
import NavigationContainer from '../navigation/NavigationContainer'
import { GlobalState, GlobalStateAction, StateProvider } from '../providers/StateContainer'
import { User } from '../models/user'

const reducer = (state: GlobalState, action: GlobalStateAction): GlobalState => {
  return {
    ...state,
    [action.key]: action.value
  };
};

export default function UserWrapper() {
  const [count, setCount] = useState(0)
  const [loading, setLoading] = useState(false)
  const userAPI = useUserAPI();
  const useAuth = useAuth0();
  const hasFetched = useRef(false);
  const [user, setUser] = useState<pond.User | undefined>(undefined)
  const [message, setMessage] = useState("Loading user profile...")
  const [global, setGlobal] = useState<undefined | GlobalState>(undefined)

  let user_id = or(useAuth.user?.sub, "")

  const loadUser = useCallback(() => {
    if (hasFetched.current) return;
    setLoading(true)
    userAPI.getUser(user_id).then(resp => {
      setUser(resp)
      setGlobal({
        user: User.create(resp),
        as: "",
        showErrors: false,
        userTeamPermissions: [],
        backgroundTasksComplete: false
      })
    }).catch(err => {
      console.log(err.toString())
      if (err.toString().includes("CORS")) {
        setMessage("CORS error")
      } else {
        setMessage("Loading failed, refresh may help")
      }
    })
    .finally(() => {
      setLoading(false)
      hasFetched.current = true;
    })
  }, [])
  
  useEffect(() => {
    if (loading) return;
    loadUser()
  }, [loading])

  if (!user || loading || !global) return (
    <LoadingScreen
      message={message}
    />
  )

  return (
    <StateProvider state={global} reducer={reducer}>
      <NavigationContainer>
        <div>
          <a href="https://vitejs.dev" target="_blank">
              <img src={viteLogo} className="logo" alt="Vite logo" />
          </a>
          <a href="https://react.dev" target="_blank">
              <img src={reactLogo} className="logo react" alt="React logo" />
          </a>
        </div>
        <h1>Vite + React</h1>
        <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
            count is {count}
        </button>
        <p>
            Hello, {user.settings?.name}!
        </p>
        </div><p className="read-the-docs">
            Coming soon
        </p>
      </NavigationContainer>
    </StateProvider>
    
  )
}