import { useEffect, useLayoutEffect, useState } from "react";
import { Box, Button, Modal, Typography } from "@mui/material";
import { enqueueSnackbar } from "notistack";
import { mutate } from "swr";

import makeRequest from "@api/makeRequest";
import { getDiscounts } from "@api/discounts";

import { useUserStore } from "@root/user";
import { parseAxiosError } from "@utils/parse-error";

import type { Discount } from "@model/discounts";

export function CheckFastlink() {
  const userId = useUserStore((state) => state.userId);
  const [discounts, setDiscounts] = useState<Discount[]>([]);
  const [askToChange, setAskToChange] = useState(false);
  const [promocode, setPromocode] = useState("");

  useEffect(() => {
    const get = async () => {
      if (!userId) {
        return;
      }

      const [discounts] = await getDiscounts(userId);

      if (discounts?.length) {
        setDiscounts(discounts);
      }
    };

    get();
  }, []);

  const fetchPromocode = async () => {
    if (promocode.length > 0) {
      try {
        const response = await makeRequest<
          { codeword: string } | { fastLink: string },
          { greetings: string }
        >({
          url:
            process.env.REACT_APP_DOMAIN + "/codeword/promocode" + "/activate",
          method: "POST",
          contentType: true,
          body: { fastLink: promocode },
        });
        enqueueSnackbar("Промокод успешно применён");
        localStorage.setItem("fl", "");
        mutate("discounts");
        return response.greetings;
      } catch (nativeError) {
        const [error] = parseAxiosError(nativeError);
        enqueueSnackbar(error);
        localStorage.setItem("fl", "");
      }
    }
  };

  useLayoutEffect(() => {
    //Промокод может быть или в урл адресе или в ЛС
    const params = new URLSearchParams(window.location.search);
    const flURL = params.get("fl");

    if (flURL !== null) {
      localStorage.setItem("fl", flURL);
      var url = new URL(window.location.href);
      url.searchParams.delete("fl");
      history.pushState(null, document.title, url);
    }

    const flLS = localStorage.getItem("fl");

    if (flLS !== null && flLS.length > 0) {
      setPromocode(flLS);

      if (userId !== null) {
        //У нас есть промокод и юзер авторизован. Проверяем есть ли у него применённый промокод
        if (discounts?.find((e) => e.Condition.User === userId)) {
          setAskToChange(true);
        } else {
          fetchPromocode();
        }
      }
    }
  }, [userId, discounts]);

  return (
    <Modal
      open={askToChange}
      onClose={() => setAskToChange(false)}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
    >
      <Box
        sx={{
          position: "absolute" as "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          bgcolor: "background.paper",
          p: 4,
          borderRadius: 2,
        }}
      >
        <Typography textAlign="center" variant="h6" component="h2">
          Заменить текущий промокод?
        </Typography>
        <Box
          sx={{
            display: "flex",
            mt: "20px",
            flexWrap: "wrap",
            justifyContent: "space-evenly",
          }}
        >
          <Button
            sx={{ margin: "5px", minWidth: " auto" }}
            variant="pena-contained-dark"
            onClick={() => {
              fetchPromocode();
              setAskToChange(false);
            }}
          >
            Да
          </Button>
          <Button
            sx={{ margin: "5px", minWidth: " auto" }}
            variant="pena-contained-dark"
            onClick={() => {
              setAskToChange(false);
              localStorage.setItem("fl", "");
            }}
          >
            Нет
          </Button>
        </Box>
      </Box>
    </Modal>
  );
}
