import { useLocation, useNavigate } from "react-router-dom";
import { makeRequest } from "@frontend/kitui";
import { useEffect, useState } from "react";
import type { GetTariffsResponse } from "@model/tariff";

import {
  Box,
  Button,
  Modal,
  Paper,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { enqueueSnackbar } from "notistack";
import { Tariff, getMessageFromFetchError } from "@frontend/kitui";
import { withErrorBoundary } from "react-error-boundary";
import { createTariffElements } from "./tariffsUtils/createTariffElements";

function TariffPage() {
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const location = useLocation();
  const navigate = useNavigate();

  const [tariffs, setTariffs] = useState();
  const [user, setUser] = useState();
  const [discounts, setDiscounts] = useState();
  const [cartTariffMap, setCartTariffMap] = useState();
  const [openModal, setOpenModal] = useState({});

  useEffect(() => {
    const get = async () => {
      const user = await makeRequest({
        method: "GET",
        url: "https://squiz.pena.digital/customer/account",
      });
      const tariffs = await makeRequest<never, GetTariffsResponse>({
        method: "GET",
        url: "https://squiz.pena.digital/strator/tariff?page=1&limit=100",
      });
      const discounts = await makeRequest({
        method: "GET",
        url: "https://squiz.pena.digital/price/discounts",
      });
      setUser(user);
      setTariffs(tariffs);
      setDiscounts(discounts.Discounts);
    };
    get();
  }, []);

  if (!user || !tariffs || !discounts) return <LoadingPage />;

  console.log("user ", user);
  console.log("tariffs ", tariffs);
  console.log("discounts ", discounts);

  const openModalHC = (tariffInfo: any) => setOpenModal(tariffInfo);
  const tryBuy = async ({ id, price }: { id: string; price: number }) => {
    openModalHC({});
    //Если в корзине что-то было - выкладываем содержимое и запоминаем чо там лежало
    if (user.cart.length > 0) {
      outCart(user.cart);
    }
    //Добавляем желаемый тариф в корзину
    await makeRequest({
      method: "PATCH",
      url: `https://hub.pena.digital/customer/cart?id=${id}`,
    });
    //Если нам хватает денежек - покупаем тариф
    if (price <= user.wallet.cash) {
      try {
        await makeRequest({
          method: "POST",
          url: "https://suiz.pena.digital/customer/cart/pay",
        });
      } catch (e) {
        enqueueSnackbar("Произошла ошибка. Попробуйте позже");
      }
      //Развращаем товары в корзину
      inCart();
    } else {
      //Деняк не хватило
      // history.pushState({}, null, "https://hub.pena.digital/wallet?action=squizpay");

      var link = document.createElement("a");
      link.href = `https://hub.pena.digital/payment?action=squizpay&dif=${
        (price - Number(user.wallet.cash)) * 100
      }`;
      document.body.appendChild(link);
      //   link.click();
    }
  };

  const purchasesAmount = user?.wallet.purchasesAmount ?? 0;
  const isUserNko = user?.status === "nko";
  const filteredTariffs = tariffs.tariffs.filter((tariff) => {
    return (
      tariff.privileges[0].serviceKey === "squiz" &&
      !tariff.isDeleted &&
      !tariff.isCustom
    );
  });

  return (
    <>
      <Box
        sx={{
          justifyContent: "left",
          mt: "40px",
          mb: "30px",
          display: "grid",
          gap: "40px",
          gridTemplateColumns: `repeat(auto-fit, minmax(300px, ${
            isTablet ? "436px" : "360px"
          }))`,
        }}
      >
        {createTariffElements(
          filteredTariffs,
          true,
          user,
          discounts,
          openModalHC,
        )}
      </Box>
      <Modal
        open={Object.values(openModal).length > 0}
        onClose={() => setOpenModal({})}
      >
        <Paper
          sx={{
            position: "absolute" as "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            boxShadow: 24,
            p: 4,
            display: "flex",
            justifyContent: "center",
            flexDirection: "column",
          }}
        >
          <Typography
            id="modal-modal-title"
            variant="h6"
            component="h2"
            mb="20px"
          >
            Вы подтверждаете платёж в сумму {openModal.price} ₽
          </Typography>
          <Button variant="contained" onClick={() => tryBuy(openModal)}>
            купить
          </Button>
        </Paper>
      </Modal>
    </>
  );
}

export const Tariffs = withErrorBoundary(TariffPage, {
  fallback: (
    <Typography mt="8px" textAlign="center">
      Ошибка загрузки тарифов
    </Typography>
  ),
  onError: () => {},
});

const LoadingPage = () => (
  <Box
    sx={{
      height: "100%",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
    }}
  >
    <Typography sx={{ textAlign: "center" }}>
      {"Подождите, пожалуйста, идёт загрузка :)"}
    </Typography>
  </Box>
);

export const inCart = () => {
  let saveCart = JSON.parse(localStorage.getItem("saveCart") || "[]");
  saveCart.forEach(async (id: string) => {
    try {
      await makeRequest({
        method: "PATCH",
        url: `https://hub.pena.digital/customer/cart?id=${id}`,
      });

      let index = saveCart.indexOf("green");
      if (index !== -1) {
        saveCart.splice(index, 1);
      }
      localStorage.setItem("saveCart", JSON.stringify(saveCart));
    } catch (e) {
      console.log("Я не смог добавить тариф в корзину :( " + id);
    }
  });
};
const outCart = (cart: string[]) => {
  //Сделаем муторно и подольше, зато при прерывании сессии данные потеряются минимально
  cart.forEach(async (id: string) => {
    try {
      await makeRequest({
        method: "DELETE",
        url: `https://suiz.pena.digital/customer/cart?id=${id}`,
      });
      let saveCart = JSON.parse(localStorage.getItem("saveCart") || "[]");
      saveCart = saveCart.push(id);
      localStorage.setItem("saveCart", JSON.stringify(saveCart));
    } catch (e) {
      console.log("Я не смог удалить из корзины тариф :(");
    }
  });
};
