const USER_PROFILE_QUERY = {
	fields: 'id, first_name, last_name, email',
}

const appId = '833399038872697'

function useFacebookAuth() {
	if (!appId) {
		throw new Error('Please provide application ID for your Facebook app!')
	}

	const responseData = Vue.reactive({
		signedIn: false,
		userData: null,
		token: null,
	})

	async function init() {
		const fb = window?.FB
		if (!fb) {
			throw new Error('Facebook SDK not loaded')
		}

		await fb.init({
			appId,
			autoLogAppEvents: true,
			xfbml: false,
			version: 'v6.0',
			cookie: true,
		})

		return new Promise((resolve) => {
			fb.getLoginStatus((res) => {
				if (res.authResponse) {
					fb.api('/me', USER_PROFILE_QUERY, (profile) => {
						Object.assign(responseData, {
							signedIn: true,
							userData: {
								id: profile.id,
								firstName: profile.first_name,
								lastName: profile.last_name,
								email: profile.email,
							},
							token: res.authResponse,
						})
						resolve(responseData)
					})
				} else {
					resolve({signedIn: false, userData: null, token: null})
				}
			}, true)
		})
	}

	function signIn() {
		const fb = window?.FB
		if (!fb) {
			throw new Error('Facebook SDK not loaded')
		}

		return new Promise((resolve, reject) => {
			fb.login((res) => {
				if (res.authResponse) {
					fb.api('/me', USER_PROFILE_QUERY, (profile) => {
						Object.assign(responseData, {
							signedIn: true,
							userData: {
								id: profile.id,
								firstName: profile.first_name,
								lastName: profile.last_name,
								email: profile.email,
							},
							token: res.authResponse,
						})
						resolve(responseData)
					})
				} else {
					reject('Login was unsuccessful!')
				}
			}, {scope: 'email'})
		})
	}

	async function signOut() {
		const fb = window?.FB
		if (!fb) {
			throw new Error('Facebook SDK not loaded')
		}

		if (!responseData.userData) {
			await fetch()
		}

		return new Promise((resolve) => {
			try {
				if (responseData?.userData?.id) {
					fb.api(`/${responseData.userData.id}/permissions`, 'DELETE', {
						access_token: responseData.token.accessToken,
					}, () => {
						Object.assign(responseData, {
							signedIn: false,
							userData: null,
							token: null,
						})
						resolve('Logged out successfully!')
					})
				} else {
					resolve('Failed to retrieve data from Facebook')
				}
			} catch (e) {
				console.error(e)
			}
		})
	}

	function fetch() {
		const fb = window?.FB
		if (!fb) {
			throw new Error('Facebook SDK not loaded')
		}

		return new Promise((resolve) => {
			fb.getAuthResponse((res) => {
				if (res.status === 'connected') {
					Object.assign(responseData, {
						signedIn: true,
						userData: {id: res.authResponse.userID},
						token: res.authResponse,
					})
					resolve(responseData)
				} else {
					resolve({signedIn: false, userData: null, token: null})
				}
			})

			resolve({signedIn: false, userData: null, token: null})
		})
	}

	return {
		responseData,
		init,
		signIn,
		signOut,
		fetch,
	}
}

window.useFacebookAuth = useFacebookAuth
