import { useEffect, useState } from "react"
import axios, { AxiosResponse } from "axios"
import { ApologyPage } from "../ApologyPage"
import { useNavigate } from "react-router-dom"
import { clearAuthToken, getMessageFromFetchError, setAuthToken, useUserAccountFetcher, useUserFetcher } from "@frontend/kitui";
import { clearUserData, setUser, setUserAccount, useUserStore } from "@root/stores/user";


function refresh(token: string) {
	return axios<never, AxiosResponse<{ accessToken: string; }>>(process.env.REACT_APP_DOMAIN + "/auth/refresh", {
		headers: {
			"Authorization": "Bearer " + token,
			"Content-Type": "application/json",
		},
		method: "POST"
	});
}

const params = new URLSearchParams(window.location.search)
const action = params.get("action")
const dif = params.get("dif")
const token = params.get("data")
const userId = params.get("userid")


let first = true

export default function QuizPayment() {
	const navigate = useNavigate()
	const [message, setMessage] = useState("Идёт загрузка")

	console.log("Я начал работать")

	if (first) {
history.pushState(null, document.title, "/quizpayment");
		try {
			first = false
			if (action && dif && token) {
				(async () => {
					// const data = await refresh(token)
					console.log(token)
					setAuthToken(token)
					// setAuthToken(data.data.accessToken)
					console.log("делаем юзера")

					useUserFetcher({
						url: process.env.REACT_APP_DOMAIN + `/user/${userId}`,
						userId,
						onNewUser: (user) => {
							setUser(user)
							navigate(`/payment?action=${action}&dif=${dif}`, { replace: true })

						},
						onError: () => { },
					})
					return
				})()
			}
		} catch (e) {
			console.log(e)
			setMessage("Произошла ошибка")
			var link = document.createElement("a");
			link.href = "https://quiz.pena.digital/tariffs";
			document.body.appendChild(link);
			link.click();
		}
	}

	return (
		<ApologyPage message={message} />
	)
};