// ---------------------------------------------------------------------------------------------------------------------
//!                                                      Imports
// ---------------------------------------------------------------------------------------------------------------------

// -------------------------------------------------- Hooks & Utils ----------------------------------------------------
import { useRouter } from 'next/navigation';
import { FormEvent } from 'react';
// ---------------------------------------------------------------------------------------------------------------------

export const useActions = ({
	userData,
	setIsPopupDisplayed,
	setUsernameMessage,
	setPasswordMessage,
}) => {
	const router = useRouter();

	const resetMessage = () => {
		setUsernameMessage(null);
		setPasswordMessage(null);
	};

	const updateUsername = async (ev: FormEvent<HTMLFormElement>) => {
		resetMessage();

		if (!ev.currentTarget.reportValidity()) {
			return;
		}

		const formData = new FormData(ev.currentTarget);

		const value = formData.get('username').toString();

		if (value == userData.username || value.length <= 1) {
			return;
		}

		const token = localStorage.getItem('token');

		try {
			const request = await fetch('/api/user', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json',
					Authorization: token,
				},
				body: JSON.stringify({
					type: 'username',
					username: value,
				}),
			});

			if (request.status == 409) {
				setUsernameMessage("Nom d'utilisateur déjà pris");
				return;
			}

			if (request.status != 200) {
				setUsernameMessage('Erreur interne. Veuillez réessayer');
				return;
			}
			setUsernameMessage("Nom d'utilisateur modifié");
		} catch (error) {
			console.error(error);

			setUsernameMessage('Erreur interne. Veuillez réessayer');
		}
	};

	const updatePassword = async (ev: FormEvent<HTMLFormElement>) => {
		ev.preventDefault();

		if (!ev.currentTarget.reportValidity()) {
			return;
		}

		resetMessage();

		const formData = new FormData(ev.currentTarget);
		const currentPassword = formData.get('currentPassword');
		const newPassword = formData.get('newPassword');
		const confirmNewPassword = formData.get('confirmNewPassword');

		const token = localStorage.getItem('token');

		if (newPassword != confirmNewPassword) {
			setPasswordMessage('Les mots de passes ne correspondent pas');
			return;
		}

		try {
			const request = await fetch('/api/user', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json',
					Authorization: token,
				},
				body: JSON.stringify({
					type: 'password',
					currentPassword,
					newPassword,
				}),
			});

			if (request.status == 403) {
				setPasswordMessage('Mauvais mot de passe');
				return;
			}
			if (request.status == 500) {
				setPasswordMessage('Erreur interne. Veuillez réessayer');
				return;
			}
			setPasswordMessage('Mot de passe modifié');
		} catch (error) {
			console.error(error);

			setPasswordMessage('Erreur interne. Veuillez réessayer');
		}
	};

	const handleClosePopup = (ev) => {
		ev.stopPropagation();
		setIsPopupDisplayed(false);
	};

	const handleDeleteUser = (ev) => {
		ev.stopPropagation();
		resetMessage();
		setIsPopupDisplayed(true);
	};

	const deleteUser = async () => {
		resetMessage();
		const token = localStorage.getItem('token');

		try {
			const request = await fetch(
				'https://lovemap-backend.vercel.app/user/delete',
				{
					method: 'DELETE',
					headers: {
						Authorization: token,
					},
				}
			);

			if (request.status != 200) {
				// setMessage('Erreur interne. Veuillez réessayer');
				return;
			}

			localStorage.clear();
			router.push('/auth/login');
		} catch (error) {
			console.error(error);
			// setMessage('Erreur interne. Veuillez réessayer');
		}
	};

	return {
		updateUsername,
		updatePassword,
		handleClosePopup,
		handleDeleteUser,
		deleteUser,
	};
};
