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,
  getAuthToken,
} from "@frontend/kitui";
import {
  clearUserData,
  setUser,
  setUserAccount,
  setUserId,
  useUserStore,
} from "@root/stores/user";
import { logout } from "@root/api/auth";
import { clearCustomTariffs } from "@root/stores/customTariffs";
import { clearTickets } from "@root/stores/tickets";
import {setNotEnoughMoneyAmount} from "@stores/cart"

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("Идёт загрузка");
  const user = useUserStore((state) => state.user);

  useEffect(
    function redirectIfSignedIn() {
      if (!first && user?._id === userId)
        navigate(`/payment?action=${action}&dif=${dif}&user=${userId}`, {
          replace: true,
        });
    },
    [navigate, user]
  );

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

  if (first) {
    history.pushState(null, document.title, "/quizpayment");
    try {
      first = false;

      if (user?._id === userId) {
        return;
      }

      if (action && dif && token) {
        (async () => {
          // const data = await refresh(token)
          // console.log(token)
          if (getAuthToken()) {
            clearAuthToken();
            clearUserData();
            clearCustomTariffs();
            clearTickets();
            setNotEnoughMoneyAmount(0)
            await logout();
          }

          setAuthToken(token);

          // setAuthToken(data.data.accessToken)
          console.log("делаем юзера ", userId);
          setUserId(userId);

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

          // 	},
          // 	onError: () => { },
          // })
          return;
        })();
      } else {
        var link = document.createElement("a");
        link.href = "https://quiz.pena.digital/tariffs";
        document.body.appendChild(link);
        link.click();
      }
    } 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} />;
}
