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'
import { Team } from '../models/team'

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

const globalDefault = {
  user: User.create(),
  team: Team.create(),
  as: "",
  showErrors: false,
  userTeamPermissions: [],
  backgroundTasksComplete: false
}

interface Props {
  toggleTheme: () => void;
}

export default function UserWrapper(props: Props) {
  const { toggleTheme } = props;
  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.getUserWithTeam(user_id).then(resp => {
      console.log(resp.data.team)
      // if (resp.data.user) setUser(resp.data.user)
      setGlobal({
        user: resp.data.user ? User.create(resp.data.user) : User.create(),
        team: resp.data.team ? Team.create(resp.data.team) : Team.create(),
        as: "",
        showErrors: false,
        userTeamPermissions: [],
        backgroundTasksComplete: false
      })
    }).catch(err => {
      console.log(err.toString())
      setGlobal(globalDefault)
    })
    .finally(() => {
      setLoading(false)
      hasFetched.current = true;
    })
  }, [setGlobal])
  
  useEffect(() => {
    if (loading) return;
    loadUser()
  }, [loading])
  
  if (loading || !global) return (
    <LoadingScreen />
  )

  return (
    <StateProvider state={global} reducer={reducer}>
      <NavigationContainer toggleTheme={toggleTheme}>
        <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, {global.user.settings?.name}!
        </p>
        </div><p className="read-the-docs">
            Coming soon
        </p>
      </NavigationContainer>
    </StateProvider>
  )
}