import { AxiosRequestConfig } from 'axios';
import useLocationInfo from '../../hooks/useLocationInfo';
import { accountClient } from '../axios';
import { LoginModel } from '../models/AccountTypes';
// import LoadUser from '../user/loadUser';
import { SetSessionExpireDate } from '../user/localStorage';
// import useAuth from './useAuth';
import { AuthenticationResult } from './useRefreshToken';
import useAuth from './useAuth';
// import useUser from './useUser';

interface IUseLogin {
	login: (login: string | undefined, password: string | undefined) => Promise<void>,
	canLogin: (login: string | undefined, password: string | undefined) => boolean,
  }

export default function useLogin(): IUseLogin {
	const { setAccessToken } = useAuth();
	// const { getUser } = useUser();
	const { getLocationInfo } = useLocationInfo();

	const login = async (login: string | undefined, password: string | undefined) => {
			if (!canLogin(login, password)) return;
			const locationInfo = await getLocationInfo();
			const response = await accountClient.post<AuthenticationResult | null>('login',
				{ login: login, password: password, ip: locationInfo?.ip } as LoginModel, 
				{ withCredentials: true } as AxiosRequestConfig
			);
			// const response = await userClient.post('login', { login: login, password: password, ip: locationInfo?.ip } as LoginModel);
			// const response = await axios.post(`${userApiUrl}login`, { login: login, password: password, ip: locationInfo?.ip } as LoginModel);
			// const response = await axios.post('https://localhost:7189/Account/login', { login: 'ko12a@ya.ru', password: '123', ip: null } as LoginModel)
            // console.log('Login Response');
            // console.log(response);
            // console.log(response);
            // console.log("response.headers['set-cookie']");
            // console.log(response.headers['set-cookie']);
			setAccessToken(response?.data?.accessToken ?? null);
			// const tokens = response?.data;
			// console.log(`loginRefreshToken: ${tokens?.refreshToken}`);
			if (response?.data?.sessionExpireDate == null){
				console.log('response?.data?.sessionExpireDate is null');
			}
			SetSessionExpireDate(response?.data?.sessionExpireDate);
			// console.log(`loginAccessToken: ${tokens?.accessToken}`);
			// const user = await LoadUser(tokens?.accessToken);
            // // console.log('Login user');
            // // console.log(user);
			// setAuth(user)
		}

	const canLogin = (login: string | undefined, password: string | undefined) => {
		return login != undefined && login.length > 0 &&
			password != undefined && password.length > 0;
	}

	return { login, canLogin };
}