import { useEffect, useState } from "react";
import { ApologyPage } from "../ApologyPage";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
  clearAuthToken,
  getMessageFromFetchError,
  setAuthToken,
  useUserAccountFetcher,
  useUserFetcher,
  getAuthToken,
} from "@frontend/kitui";
import {
  clearUserData,
  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 { cancelPayCartProcess, setAction, setBackWay, setFromDomain, setNotEnoughMoneyAmount, startPayCartProcess } from "@stores/allTypesOfPurchases"
import { Action, FromDomain } from "@root/model/autoPay";
import { logoutAndRedirect, clearUserSession } from "@root/utils/logout";
//http://localhost:3001/payment?fromdomain=localhost:3000&action=buy&dif=96900&userid=68773ec66816e2c659b36dad&sec=
let first = true;

export default function AnyServicePayment() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [message, setMessage] = useState("Идёт загрузка");
  const user = useUserStore((state) => state.user);

  let URLfromDomain = searchParams.get("fromdomain");//домен откуда произошёл запрос на финансовые работы
  let URLaction = searchParams.get("action");//что мы, собсна, хотим: оплатить, пополнить, купить и создать квиз
  let URLuserId = searchParams.get("userid");//тот кто начал всё это действо
  const URLwayBack = searchParams.get("wayback") ?? "";//путь по которому нужно будет пройти после того как закончим манипуляции (без домена)
  let URLmoneyDifferent = Number(searchParams.get("dif"));//сколько нужно деняк
  let URLtoken = searchParams.get("sec");
  const URLadditionalinformation = searchParams.get("additionalinformation") ?? "";//дополнительная информация

  useEffect(
    function redirectIfSignedIn() {
      console.log("---------------------------")
      console.log(URLfromDomain)
      console.log(URLaction)
      console.log(URLuserId)
      console.log(URLwayBack)
      console.log(URLmoneyDifferent)
      console.log(URLtoken)
      console.log(URLadditionalinformation)
      console.log("---------------------------")
      if (!first && user?._id === URLuserId) {
        let returnUrl = `/payment?fromdomain=${URLfromDomain}&action=${URLaction}&dif=${URLmoneyDifferent}&userid=${URLuserId}`
        if (URLwayBack) returnUrl += `&wayback=${URLwayBack}`
        if (URLadditionalinformation) returnUrl += `&additionalinformation=${URLadditionalinformation}`
        console.log("AnyServicePayment - формируем URL для payment:", returnUrl);
        navigate(returnUrl, {
          replace: true,
        });
      }
    },
    [navigate, user]
  );

  if (first) {
    navigate(`/anyservicepayment`, {
      replace: true,
    });
    try {
      first = false;

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

      if (URLaction && URLmoneyDifferent && URLtoken) {
        (async () => {
          if (getAuthToken()) {
            logoutAndRedirect(navigate);
            await logout();
          }

          setAuthToken(URLtoken);
          setUserId(URLuserId);
          return;
        })();
      } else {
        var link = document.createElement("a");
        link.href = `https://${URLfromDomain}/${URLwayBack}`;
        document.body.appendChild(link);
        link.click();
      }
    } catch (e) {
      setMessage("Произошла ошибка");
      var link = document.createElement("a");
      link.href = `https://${URLfromDomain}/${URLwayBack}`;
      document.body.appendChild(link);
      link.click();
    }
  }

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