import { useState, useRef, useLayoutEffect } from "react";
import ChartIcon from "@icons/ChartIcon";
import LinkIcon from "@icons/LinkIcon";
import PencilIcon from "@icons/PencilIcon";
import { Quiz } from "@model/quiz/quiz";
import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
import {
  Box,
  Button,
  IconButton,
  Typography,
  useMediaQuery,
  useTheme,
  Popover,
} from "@mui/material";
import { deleteQuiz, setEditQuizId } from "@root/quizes/actions";
import { Link, useNavigate } from "react-router-dom";
import { inCart } from "../../pages/Tariffs/Tariffs";
import { makeRequest } from "@frontend/kitui";
import { enqueueSnackbar } from "notistack";
import { useDomainDefine } from "@utils/hooks/useDomainDefine";

interface Props {
  quiz: Quiz;
  openCount?: number;
  applicationCount?: number;
  conversionPercent?: number;
}

export default function QuizCard({
  quiz,
  openCount = 0,
  applicationCount = 0,
  conversionPercent = 0,
}: Props) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const navigate = useNavigate();
  const [subMenuOpen, setSubMenuOpen] = useState<boolean>(false);
  const subMenuRef = useRef<HTMLButtonElement | null>(null);
  const { isTestServer } = useDomainDefine();
  function handleEditClick() {
    setEditQuizId(quiz.backendId);
    navigate("/edit");
  }

  const questionCount = useRef(quiz.questions_count.toString() || "");

  useLayoutEffect(() => {
    const pay = async () => {
      try {
        await makeRequest({
          method: "POST",
          url: process.env.REACT_APP_DOMAIN + "/customer/cart/pay",
        });
        inCart();
      } catch (e) {
        enqueueSnackbar(
          "Попробуйте снова купить тариф после зачисления средств",
        );
      }
    };
    const params = new URLSearchParams(window.location.search);
    const fromSquiz = params.get("action");
    if (fromSquiz === "fromhub") {
      window.history.replaceState(null, "", "/list");
      pay();
    }
  }, []);

  return (
    <Box
      data-cy="quiz-card"
      sx={{
        display: "flex",
        flexDirection: "column",
        backgroundColor: "white",
        width: "560px",
        height: "280px",
        p: "20px",
        borderRadius: "12px",
        boxSizing: "border-box",
        boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
                            0px 41.7776px 129.093px rgba(210, 208, 225, 0.172525), 
                            0px 22.3363px 69.0192px rgba(210, 208, 225, 0.143066),
                            0px 12.5216px 38.6916px rgba(210, 208, 225, 0.12),
                            0px 6.6501px 20.5488px rgba(210, 208, 225, 0.0969343),
                            0px 2.76726px 8.55082px rgba(210, 208, 225, 0.0674749)`,
      }}
    >
      <Typography
        sx={{
          textOverflow: "ellipsis",
          overflow: "hidden",
          whiteSpace: "nowrap",
          widows: "100%",
          maxWidth: "280px",
        }}
        variant="h5"
      >
        {quiz.name}
      </Typography>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          mt: "10px",
          gap: "10px",
        }}
      >
        <LinkIcon bgcolor="#EEE4FC" color={theme.palette.brightPurple.main} />
        <Typography
          color={theme.palette.grey3.main}
          sx={{
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            maxWidth: "300px",
          }}
          component={Link}
          target="_blank"
          to={
            isTestServer
              ? "https://s.hbpn.link/" + quiz.qid
              : "https://hbpn.link/" + quiz.qid
          }
        >
          {isTestServer
            ? `https://s.hbpn.link/${quiz.qid}`
            : `https://hbpn.link/${quiz.qid}`}
        </Typography>
      </Box>
      <Box
        sx={{
          display: "flex",
          mt: "32px",
          mr: "22px",
        }}
      >
        <Box sx={{ flex: "1 1 0" }}>
          <Typography variant="h5">{openCount}</Typography>
          <Typography color={theme.palette.grey3.main}>Открытий</Typography>
        </Box>
        <Box sx={{ flex: "1 1 0" }}>
          <Typography variant="h5">{applicationCount}</Typography>
          <Typography color={theme.palette.grey3.main}>Заявок</Typography>
        </Box>
        <Box sx={{ flex: "1 1 0" }}>
          <Typography variant="h5">{conversionPercent} %</Typography>
          <Typography color={theme.palette.grey3.main}>Конверсия</Typography>
        </Box>
      </Box>
      <Box
        sx={{
          mt: "auto",
          display: "flex",
          gap: isMobile ? "10px" : "20px",
        }}
      >
        <Button
          variant="contained"
          sx={{
            padding: "10px 39px",
          }}
          onClick={() => {
            navigate(`/results/${quiz.backendId}`);
            setEditQuizId(quiz.backendId);
          }}
        >
          Заявки
        </Button>
        <Button
          variant="outlined"
          startIcon={<PencilIcon />}
          onClick={handleEditClick}
          sx={{
            padding: isMobile ? "10px" : "10px 20px",
            minWidth: "unset",
            color: theme.palette.brightPurple.main,
            "& .MuiButton-startIcon": {
              marginRight: isMobile ? 0 : "4px",
              marginLeft: 0,
            },
          }}
        >
          {isMobile ? "" : "Редактировать"}
        </Button>
        {/* <Button
          variant="outlined"
          startIcon={<ChartIcon />}
          sx={{
            minWidth: "46px",
            padding: "10px 10px",
            "& .MuiButton-startIcon": {
              mr: 0,
              ml: 0,
            },
          }}
        /> */}
        <IconButton
          ref={subMenuRef}
          sx={{
            color: theme.palette.brightPurple.main,
            ml: "auto",
          }}
          onClick={() => setSubMenuOpen(true)}
          data-cy="delete-quiz"
        >
          <MoreHorizIcon sx={{ transform: "scale(1.75)" }} />
        </IconButton>
        <Popover
          open={subMenuOpen}
          anchorEl={subMenuRef.current}
          onClose={() => setSubMenuOpen(false)}
          anchorOrigin={{ vertical: "top", horizontal: "right" }}
        >
          <Box onClick={() => setSubMenuOpen(false)}>
            {/* <Button
                            sx={{
                                display: "block",
                                width: "100%",
                                padding: "15px 30px",
                            }}
                            onClick={()=>{}}
                        >
                            Копировать
                        </Button> */}
            <Button
              id="deleteButton"
              sx={{
                display: "block",
                width: "100%",
                padding: "15px 30px",
              }}
              onClick={() => deleteQuiz(quiz.id)}
            >
              Удалить
            </Button>
          </Box>
        </Popover>
      </Box>
    </Box>
  );
}
