import { useState, useEffect } from "react";
import {
  Box,
  Button,
  Typography,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import { payCart } from "@root/api/cart";
import { useUserStore } from "@root/stores/user";
import wallet_icon from "@root/assets/Icons/ColorWallet.svg";
import { Link, useSearchParams } from "react-router-dom";

const MINUTE = 1000 * 60;

export default () => {
  const [redirectUrl, setRedirectUrl] = useState<string>("/");
  const theme = useTheme();
  const phone = useMediaQuery(theme.breakpoints.down(375));
  const userId = useUserStore((state) => state.user?._id);
  const [searchParams] = useSearchParams();
  const paymentUserId = searchParams.get("userid");

  useEffect(() => {
    const from = searchParams.get("from") || "hub";
    const purpose = searchParams.get("purpose");

    if (purpose === "paycart" || from !== "quiz") {
      let tryCount = 0;

      if (userId !== paymentUserId) {
        return;
      }

      const payCartPendingRequestDeadline = localStorage.getItem(
        "payCartPendingRequestDeadline"
      );
      const deadline = payCartPendingRequestDeadline
        ? Number(payCartPendingRequestDeadline)
        : Date.now() + 20 * MINUTE;

      localStorage.setItem(
        "payCartPendingRequestDeadline",
        deadline.toString()
      );

      tryPayCart();

      async function tryPayCart() {
        tryCount += 1;

        const [, payCartError] = await payCart();

        if (!payCartError || Date.now() > deadline) {
          localStorage.removeItem("payCartPendingRequestDeadline");
          return;
        }

        setTimeout(tryPayCart, tryCount > 5 ? MINUTE : MINUTE / 6);
      }
    }

    const host = window.location.hostname;
    const domain = (host.includes("s") ? "s" : "") + from;
    const pathname = from === "hub" ? "/tariffs" : "/list";

    setRedirectUrl(
      `https://${domain}.pena.digital${pathname}?afterpay=${true}&userid=${userId}`
    );
  }, []);

  return (
    <Box
      sx={{
        width: "100vw",
        height: "100vh",
        p: phone ? "76px 16px" : "117px 0 0 0",
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Box
          component="img"
          src={wallet_icon}
          sx={{
            width: phone ? "338px" : "auto",
            height: phone ? "215px" : "auto",
            mb: "60px",
          }}
        />
        <Typography
          sx={{
            fontSize: phone ? "24px" : "36px",
            fontWeight: 500,
            lineHeight: "28.44px",
            textAlign: "center",
            mb: "10px",
          }}
        >
          Спасибо за оплату!
        </Typography>
        <Typography
          sx={{
            fontSize: "18px",
            lineHeight: "21.33px",
            textAlign: "center",
            color: theme.palette.gray.dark,
            mb: "30px",
          }}
        >
          Ваш платеж принят и в течение 10 минут товары будут зачислены
        </Typography>
        <Button
          component={Link}
          to={redirectUrl.toString()}
          replace={true}
          variant="pena-contained-dark"
        >
          На главную
        </Button>
      </Box>
    </Box>
  );
};
