import defaultUser from '../models/defaultUser'
import User, {UserFormValues, UserPreferences} from '../models/user'
import {hookstate} from '@hookstate/core'
import {localstored} from '@hookstate/localstored'
import agent from '../api/agent'
import globalRouter from "../api/globalRouter";

export const loggedInUser = hookstate(defaultUser as User)
export const userToken = hookstate('')
export const loggedInState = hookstate(false)
export const appLoadedState = hookstate(false)
export const adminMode = hookstate(false)
export const loadedPreferences = hookstate({} as UserPreferences)
export const userPreferences = hookstate([] as UserPreferences[],
    localstored({
        key: 'userPreferences'
    }))

export const createUser = async (creds: UserFormValues) => {
    try {
        const user = await agent.Account.register(creds)
        setToken(user.token)
        await getUser(user.token)
        loggedInState.set(true)
        if (globalRouter.navigate) globalRouter.navigate('/games')
    } catch (error) {
        throw error
    }
}

export const login = async (creds: UserFormValues) => {
    try {
        const user = await agent.Account.login(creds)
        setToken(user.token)
        await getUser(user.token)
        loggedInState.set(true)
        if (globalRouter.navigate) globalRouter.navigate('/games')
    } catch (error) {
        throw error
    }
}

export const logout = () => {
    adminMode.set(false)
    setToken('')
    window.localStorage.removeItem('jwt')
    loggedInUser.set(defaultUser)
    loggedInState.set(false)
    if (globalRouter.navigate) globalRouter.navigate('/')
}

export const setToken = (token: string) => {
    if (token.length > 1) window.localStorage.setItem('jwt', token)
    userToken.set(token)
}

export const adminModeToggle = () => {
    adminMode.set(toggle => !toggle)
    const toggle = adminMode.get()
    if (toggle) {
        window.localStorage.setItem('admin', 'active')
    } else {
        window.localStorage.removeItem('admin')
    }
}

export const getUser = async (token: string) => {
    try {
        userToken.set(token)
        const user = await agent.Account.current()
        loggedInState.set(true)
        loggedInUser.set(user.data)
        const userPreferencesExist = userPreferences.get().findIndex(x => x.id == user.data._id)
        if(userPreferencesExist === -1) {
            userPreferences.merge([{
                id: user.data._id,
                theme: 'light',
                stickyNav: true,
            }])
        }
        const currentPreferences = userPreferences.get().filter(x => x.id == user.data._id)
        loadedPreferences.set({
            id: currentPreferences[0].id,
            theme: currentPreferences[0].theme,
            stickyNav: currentPreferences[0].stickyNav
        })
    } catch (error) {
        console.error(error)
    }
}

export const updateUserPreferences = async (pref: UserPreferences) => {
    try {
        const user = await agent.Account.current()
        const foundIndex = userPreferences.get().findIndex(x => x.id === user.data._id)
        userPreferences[foundIndex].set(pref)
        loadedPreferences.set(pref)
    } catch (err) {
        console.error(err)
    }
}

export const setAppLoaded = (bool: boolean) => appLoadedState.set(bool)
