import React, {createContext, useEffect, useReducer} from "react";

import Loader from "@/components/loader";
import {getAuthToken, setAuthToken} from "@/hooks/useAuth.ts";
import {auth} from "@/service/api/user.ts";

const UserRoleStorageKey = 'user-current-role';

function removeRoleStorage() {
	localStorage.removeItem(UserRoleStorageKey)
}

type AuthAction = { action?: string, payload: Partial<AuthProps> }

// 权限相关 context
const AuthContext = createContext<AuthContextType | null>(null)

// 权限相关初始化数据
const initialState: AuthProps = {
	isLoggedIn: false,
	isInitialized: false,
	user: null
};

// 状态 reducer
const authReducer = (prevState: AuthProps, {payload}: AuthAction) => {
	return {
		...prevState,
		...payload,
	} as AuthProps
}

export const AuthProvider = ({children}: { children: React.ReactNode }) => {
	const [state, dispatch] = useReducer(authReducer, initialState);

	// MOCK INIT DATA
	const init = async () => {
		const token = getAuthToken();
		if (token) {
			const result = localStorage.getItem(AppConfig.AUTHED_PERSON_DATA_KEY)
			if (result) {
				const user = JSON.parse(result) as UserProfile
				dispatch({
					payload: {
						isInitialized: true,
						isLoggedIn: true,
						user,
						token
					}
				})
				return 'initialized'
			}
		}
		dispatch({
			payload: {
				isInitialized: true,
				user: null,
				token: null
			}
		})
		return 'initialized'
	}
	// 登录
	const login = async (code: string, state: string) => {
		const ret = await auth(code, state)
		// 保存token
		setAuthToken(ret.token, ret.user_info, -1);

		//
		dispatch({
			action: 'login',
			payload: {
				isLoggedIn: true,
				token: ret.token,
				user: ret.user_info
			}
		})
	}
	// 登出
	const logout = async () => {
		setAuthToken(null,null,-1)
		removeRoleStorage()
		dispatch({
			action: 'logout',
			payload: {
				isLoggedIn: false,
				user: null
			}
		})
	}

	const updateUser = async (user: Partial<UserProfile>) => {
		dispatch({
			action: 'updateUser',
			payload: {
				user: {
					...state.user,
					...user
				} as never,

			}
		})
	};

	useEffect(() => {
		init().then(console.log)
	}, [])

	// 判断是否已经初始化
	if (state.isInitialized !== undefined && !state.isInitialized) {
		return <Loader/>;
	}
	return (<AuthContext.Provider value={{
		...state,
		login,
		logout,
		updateUser
	}}>{children}</AuthContext.Provider>)
}
export default AuthContext