import { useEffect, useState } from "react";
import axios from "axios";
import { useUser } from "../hooks/useUser";

const BASE_URL = "https://staysafe.deligraph.info/wp-json/wp/v2";
const BASE_CUSTOM_URL = "https://staysafe.deligraph.info/wp-json/lhoist-datas";
const WORDPRESS_API_TOKEN = process.env.REACT_APP_WORDPRESS_API_TOKEN;

const UMAMI_API_TOKEN = process.env.REACT_APP_UMAMI_API_TOKEN;
const UMAMI_WEBSITE_ID = process.env.REACT_APP_UMAMI_WEBSITE_ID;
const UMAMI_API_BASE_ENDPOINT = process.env.REACT_APP_UMAMI_API_BASE_ENDPOINT;

const umamiBaseEndpoint = process.env.REACT_APP_UMAMI_API_BASE_ENDPOINT;

function useWordpressCustomData(url) {
	const [data, setData] = useState();
	const { language } = useUser();
	const fullUrl = `${BASE_CUSTOM_URL}${url}?current-language=${language}`;

	useEffect(() => {
		const dataFetch = async () => {
			const data = await (await fetch(fullUrl)).json();

			setData(data);
		};

		dataFetch();
	}, [language, fullUrl]);

	return data;
}
function useWordpressData(url) {
	const [data, setData] = useState();

	useEffect(() => {
		const dataFetch = async () => {
			const data = await (await fetch(BASE_URL + url)).json();

			setData(data);
		};

		dataFetch();
	}, [url]);

	return data;
}

async function postGameStatisticsData() {
	const locals = ["FR", "BE", "DE", "NL", "UK", "US", "FR"];
	const countries = ["France", "Belgique", "Deutschland", "Nederland", "United Kingdom", "United States"];
	const scores = [4, 2, 1, 3, 0, 5];
	const completionTimes = [2000, 3000, 4000, 5000, 6000, 7000];

	const randomeIndex = Math.floor(Math.random() * locals.length);

	const requestData = {
		user_locale: locals[randomeIndex],
		user_country: countries[randomeIndex],
		level_post_id: 43,
		level_score: scores[randomeIndex],
		level_completion_time: completionTimes[randomeIndex],
	};

	var requestHeaders = new Headers();
	requestHeaders.append("Content-Type", "application/json");
	requestHeaders.append("Authorization", `Bearer ${WORDPRESS_API_TOKEN}`);

	try {
		const response = await fetch("https://staysafe.deligraph.info/wp-json/lhoist-datas/statistics/post", {
			method: "POST",
			headers: requestHeaders,
			body: JSON.stringify(requestData),
		});

		console.log("Réponse reçue:", requestData);
		// console.log("Réponse reçue:", response);

		if (!response.ok) {
			throw new Error(
				`Erreur lors de la récupération des données depuis ${
					BASE_CUSTOM_URL + "/statistics/post"
				}`
			);
		}

		const responseData = await response.json();
		return responseData;
	} catch (error) {
		console.error(error);
	}
}

function useUmamiDatas() {
	const umamiUrl = "https://umami.deligraph.be/api/websites";
	const bearerToken =
		"Ii96P0XNdBE0gD0l8lX5Qf3+Lt7T0RsEoWUjf8qNaifyPbhi/PXmGygkIHuGbMm6bJ9iHPe9pIzfBJeFvG+ehlQSd4MWuWr3xKEmxtcwDMOlN4aDo3rlSf9phB02sjx0QcBhngfl0p9g/nI30d1XTWvHspw5BCNT7+NRzb5gDa24tbbSS/a/wL9+TN+mCjCUsaMOt9o/t0D3kNtE6qSgK4gAFijbDBXsgjbiPwb3HemrEb19JfY9gtMMpwBVE2KKst0j6kyKUWWDeJiBz3LQHO+FSthwG9tQCovVFgHNzLh+L+6fcmUkEpDC3nA62UCPmVAy3zJgjFWgtVZdXaSeFm7mLF1/Wsqk3g==";

	const [data, setData] = useState();

	useEffect(() => {
		const dataFetch = async () => {
			const data = await (
				await fetch(umamiUrl, {
					method: "GET",
					headers: {
						"Content-Type": "application/json",
						Authorization: `Bearer ${bearerToken}`,
					},
				})
			).json();

			setData(data);
		};

		dataFetch();
	}, []);
	return data;
}

function useUmamiUpdateDatas() {
	const [result, setResult] = useState(null); // État local pour stocker le résultat

	const eventName = "event-name-de-test";

	const UMAMI_SEND_URL = UMAMI_API_BASE_ENDPOINT + "/send";

	const dataPayload = {
		payload: {
			hostname: window.location.hostname,
			language: navigator.language,
			referrer: document.referrer,
			screen: `${window.screen.width}x${window.screen.height}`,
			title: document.title,
			url: window.location.pathname,
			website: UMAMI_WEBSITE_ID,
			name: "puzzle-1-complete",
			data: {
				lang: "fr",
				country: "France",
				level_post_id: 154,
				level_is_completed: 0,
				level_completion_time: 20000,
				level_score: 12,
			},
		},
		type: "event",
	};
	useEffect(() => {
		const dataFetch = async () => {
			try {
				await axios.post(UMAMI_SEND_URL, dataPayload, {
					headers: {
						"User-Agent": navigator.userAgent,
					},
				});
				setResult(`Event '${eventName}' sent successfully to Umami.`);
				console.log(`Event '${eventName}' sent successfully to Umami.`);
			} catch (error) {
				setResult("Error sending Umami event:");
				console.error("Error sending Umami event:", error);
			}
		};

		dataFetch();
	}, []);
	return result;
}

export { useWordpressData, useWordpressCustomData, postGameStatisticsData, useUmamiDatas, useUmamiUpdateDatas };
