import { activatePromocode } from "@api/promocode";
import { useToken } from "@frontend/kitui";
import ArrowLeft from "@icons/questionsPage/arrowLeft";
import {
  Box,
  Button,
  Container,
  IconButton,
  Modal,
  Paper,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useUserStore } from "@root/user";
import { LogoutButton } from "@ui_kit/LogoutButton";
import { useDomainDefine } from "@utils/hooks/useDomainDefine";
import { enqueueSnackbar } from "notistack";
import { useEffect, useState } from "react";
import { withErrorBoundary } from "react-error-boundary";
import { Link, useNavigate } from "react-router-dom";
import Logotip from "../../pages/Landing/images/icons/QuizLogo";
import CollapsiblePromocodeField from "./CollapsiblePromocodeField";
import { Tabs } from "./Tabs";
import { createTariffElements } from "./tariffsUtils/createTariffElements";
import { currencyFormatter } from "./tariffsUtils/currencyFormatter";
import { useWallet, setCash } from "@root/cash";
import { handleLogoutClick } from "@utils/HandleLogoutClick";
import { cartApi } from "@api/cart";

import { Other } from "./pages/Other";
import { ModalRequestCreate } from "./ModalRequestCreate";
import { cancelCC, useCC } from "@/stores/cc";
import { NavSelect } from "./NavSelect";
import { useTariffs } from '@utils/hooks/useTariffs';
import { useDiscounts } from '@utils/hooks/useDiscounts';

const StepperText: Record<string, string> = {
  day: "Тарифы на время",
  count: "Тарифы на объём",
  dop: "Доп. услуги",
};

function TariffPage() {
  const userPrivilegies = useUserStore(store => store.userAccount?.privileges);
  const theme = useTheme();
  const token = useToken();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const userId = useUserStore((state) => state.userId);
  const navigate = useNavigate();
  const user = useUserStore((state) => state.customerAccount);
  const a = useUserStore((state) => state.customerAccount); //c wallet
  console.log("________________34563875693785692576_____________USERRRRRRR")
  console.log(a)
  const { data: discounts } = useDiscounts(userId);
  const [isRequestCreate, setIsRequestCreate] = useState(false);
  const [openModal, setOpenModal] = useState({});
  const { cashString, cashCop, cashRub } = useWallet();
  const [selectedItem, setSelectedItem] = useState<TypePages>("day");
  const { isTestServer } = useDomainDefine();
  const [promocodeField, setPromocodeField] = useState<string>("");
  const cc = useCC(store => store.cc)


  const { data: tariffs, error: tariffsError, isLoading: tariffsLoading } = useTariffs();

console.log("________34563875693785692576_____ TARIFFS")
console.log(tariffs)

  useEffect(() => {
    if (a) {
      let cs = currencyFormatter.format(Number(user.wallet.cash) / 100);
      let cc = Number(user.wallet.cash);
      let cr = Number(user.wallet.cash) / 100;
      setCash(cs, cc, cr);
    }
  }, [a]);

  useEffect(() => {
    if (cc) {
      setIsRequestCreate(true)
      cancelCC()
    }
  }, [])
  if (!user || !tariffs || !discounts) return <LoadingPage />;

  const openModalHC = (tariffInfo: any) => setOpenModal(tariffInfo);
  const tryBuy = async ({ id, price }: { id: string; price: number }) => {
    openModalHC({});
    //Если в корзине что-то было - выкладываем содержимое и запоминаем чо там лежало
    if (user.cart.length > 0) {
      outCart(user.cart);
    }
    //Добавляем желаемый тариф в корзину
    const [_, addError] = await cartApi.add(id);

    if (addError) {
      //Развращаем товары в корзину
      inCart();

      return;
    }

    //Если нам хватает денежек - покупаем тариф
    const [data, payError] = await cartApi.pay();

    if (payError || !data) {
      //если денег не хватило
      if (payError?.includes("insufficient funds") || payError?.includes("Payment Required")) {
        let cashDif = Number(payError.split(":")[1]);
        var link = document.createElement("a");
        link.href = `https://${isTestServer ? "s" : ""}hub.pena.digital/quizpayment?action=squizpay&dif=${cashDif}&data=${token}&userid=${userId}`;
        if (cc) link.href = link.href + "&cc=true"//после покупки тарифа и возвращения будем знать что надо открыть модалку
        document.body.appendChild(link);
        link.click();
        return;
      }

      //другая ошибка
      enqueueSnackbar("Произошла ошибка. Попробуйте позже");

      return;
    }

    setCash(
      currencyFormatter.format(Number(data.wallet.cash) / 100),
      Number(data.wallet.cash),
      Number(data.wallet.cash) / 100,
    );

    //cc - пометка что мы хотим заказать квиз. Если хотели, то открываем модалку
    if (cc) setIsRequestCreate(true)
    cancelCC()//но в любом случае в конце перехотим
    enqueueSnackbar("Тариф успешно приобретён");

    //Развращаем товары в корзину
    inCart();
  };

  const filteredTariffs = tariffs.filter((tariff, i) => {
    return (
      tariff.privileges[0].serviceKey === "squiz" &&
      !tariff.isDeleted &&
      !tariff.isCustom &&
      tariff.privileges[0]?.type === selectedItem
    );
  });


  const filteredBaseTariffs = filteredTariffs.filter((tariff) => {
    return tariff.privileges[0].privilegeId !== "squizHideBadge";
  });

  async function handleApplyPromocode() {
    if (!promocodeField) return;

    const [greetings, error] = await activatePromocode(promocodeField);

    if (error) {
      enqueueSnackbar(error);
      return;
    }

    enqueueSnackbar(greetings);
  }

  const startRequestCreate = () => {
    setIsRequestCreate(true)
  }

  if (!a) return null;
  return (
    <>
      <Container
        component="nav"
        disableGutters
        maxWidth={false}
        sx={{
          px: "16px",
          display: "flex",
          height: "80px",
          alignItems: "center",
          gap: isMobile ? "7px" : isTablet ? "20px" : "60px",
          flexDirection: "row",
          justifyContent: "space-between",
          bgcolor: "white",
          borderBottom: "1px solid #E3E3E3",
        }}
      >
        <Link to="/">
          <Logotip width={124} />
        </Link>
        <IconButton onClick={() => navigate("/list")}>
          <ArrowLeft color="black" />
        </IconButton>
        <Box sx={{ display: "flex", ml: "auto" }}>
          <Box sx={{ whiteSpace: "nowrap" }}>
            <Typography
              sx={{
                fontSize: "12px",
                lineHeight: "14px",
                color: "gray",
              }}
            >
              Мой баланс
            </Typography>
            <Typography
              variant="body2"
              color={"#7e2aea"}
              fontSize={
                isMobile ? (cashString.length > 9 ? "13px" : "16px") : "16px"
              }
            >
              {cashString}
            </Typography>
          </Box>
          <LogoutButton
            onClick={() => {
              navigate("/");
              handleLogoutClick();
            }}
            sx={{
              ml: "20px",
            }}
          />
        </Box>
      </Container>
      <Box
        sx={{
          p: "25px",
          pb: 0,
        }}
      >
        <CollapsiblePromocodeField
          fieldValue={promocodeField}
          onFieldChange={setPromocodeField}
          onPromocodeApply={handleApplyPromocode}
        />
      </Box>
      {isMobile ?
        <NavSelect
          selectedItem={selectedItem}
          setSelectedItem={setSelectedItem}
        />
        :
        <Tabs
          names={Object.values(StepperText)}
          items={Object.keys(StepperText)}
          selectedItem={selectedItem}
          setSelectedItem={setSelectedItem}
          toDop={() => setSelectedItem("dop")}
        />
      }


      <Box
        sx={{
          justifyContent: "left",
          display: selectedItem === "dop" ? "flex" : "grid",
          gap: "40px",
          p: "20px",
          gridTemplateColumns: `repeat(auto-fit, minmax(300px, ${isTablet ? "436px" : "360px"
            }))`,
          flexDirection: selectedItem === "dop" ? "column" : undefined,
        }}
      >
        {selectedItem === "day" &&
          createTariffElements(
            filteredBaseTariffs,
            true,
            user,
            discounts,
            openModalHC,
          )}
        {selectedItem === "count" &&
          createTariffElements(
            filteredTariffs,
            true,
            user,
            discounts,
            openModalHC,
          )}
        {(selectedItem === "dop" || selectedItem === "hide" || selectedItem === "create")
          && (
            <Other
              selectedItem={selectedItem}
              content={[
                {
                  title: `Убрать логотип "PenaQuiz"`,
                  onClick: () => setSelectedItem("hide")
                },
                {
                  title: "Создать квиз на заказ",
                  onClick: () => setSelectedItem("create")
                },
              ]}

              tariffs={tariffs}
              user={user}
              discounts={discounts}
              openModalHC={openModalHC}
              userPrivilegies={userPrivilegies}
              startRequestCreate={startRequestCreate}
            />
          )}
      </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 ? openModal.price.toFixed(2) : 0} ₽
          </Typography>
          <Button variant="contained" onClick={() => tryBuy(openModal)}>
            купить
          </Button>
        </Paper>
      </Modal>
      <ModalRequestCreate open={isRequestCreate} onClose={() => setIsRequestCreate(false)} />
    </>
  );
}

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

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

export const inCart = () => {
  let saveCart = JSON.parse(localStorage.getItem("saveCart") || "[]");
  if (Array.isArray(saveCart)) {
    saveCart.forEach(async (id: string) => {
      const [_, addError] = await cartApi.add(id);

      if (addError) {
        console.error(addError);
      } else {
        let index = saveCart.indexOf("green");

        if (index !== -1) {
          saveCart.splice(index, 1);
        }

        localStorage.setItem("saveCart", JSON.stringify(saveCart));
      }
    });
  } else {
    localStorage.setItem("saveCart", "[]");
  }
};
export const outCart = (cart: string[]) => {
  //Сделаем муторно и подольше, зато при прерывании сессии данные потеряются минимально
  if (cart.length > 0) {
    cart.forEach(async (id: string) => {
      const [_, deleteError] = await cartApi.delete(id);

      if (deleteError) {
        console.error(deleteError);
        cancelCC()//мы хотели открыть модалку после покупки тарифа на создание квиза, но не вышло и модалку не откроем

        return;
      }

      let saveCart = JSON.parse(localStorage.getItem("saveCart") || "[]") || [];
      if (!Array.isArray(saveCart)) saveCart = []
      saveCart = saveCart.push(id);
      localStorage.setItem("saveCart", JSON.stringify(saveCart));
    });
  }

};
