import { atom, useAtom } from 'jotai';
import { accountClient } from '../axios';
import { User, UserInfo } from '../models/AccountTypes';
import { IsSessionActive } from '../user/localStorage';
import useAuth from './useAuth';
import useAxiosWithAuth from './useAxiosWithAuth';
import GetUser, { GetAvatar } from '../UserApi';

const userAtom = atom<User | null>(null);
export interface IUseUser {
	getUser: () => Promise<UserInfo | null>,
	forceReloadUser: () => Promise<void>,
  }

export default function useUser(): IUseUser {
	const [ user, setUser ] = useAtom(userAtom);
	const { accessToken } = useAuth();
	useAxiosWithAuth(accountClient);
	
	const userToUserInfo = async (user: User | null, accessToken : string | null | undefined) =>{
		if (user == null){
			return null;
		}
		else{
			const result = {
				id: user.id,
				accountId: user.accountId,
				sessionId: user.sessionId,
				nickName: user.nickName,
				firstName: user.firstName,
				patronymic: user.patronymic,
				lastName: user.lastName,
				birthDate: user.birthDate,
				languageId: user.languageId,
				email: user.languageId,
				// isAuthenticated: getUserResponse.data.isAuthenticated && accessToken != null,
				isAuthenticated: user.isAuthenticated,
				accessToken: accessToken ?? null,
				avatarData: await GetAvatar(accessToken ?? null),
			} as UserInfo;

			return result;
		}
	}

	const getUser = async (forceReload?: boolean | null) => {
		// console.log(`AccessToken: ${accessToken}`);
		if (user != null && forceReload != true){
			if (IsSessionActive()){
				return userToUserInfo(user, accessToken);
			}
			else{
				setUser(null);
				return null;
			}
		}
		else if (IsSessionActive()){
			return new Promise<UserInfo | null>((resolve, reject) => {
				// LoadUser(null)
				GetUser(null, null)
				.then((user) => {
					setUser(user);
					resolve(userToUserInfo(user, accessToken));
				})
				.catch(() => {
					setUser(null);
					reject(null);
				})
			})
			// const loadedUser = await LoadUser(null);
			// // console.log('loaded user');
			// // console.log(loadedUser);
			// setUser(loadedUser);
			// return userToUserInfo(loadedUser, accessToken);
		}
		else{
			setUser(null);
			// console.log('here1');
			return null;
		}
	};

	const forceReloadUser = async () => new Promise<void>((resolve) => getUser(true).finally(() => resolve()));
	return { getUser, forceReloadUser };
}