import { useEffect, useState } from "react";

import { updateQuiz } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";

import { SwitchSetting } from "../SwichResult";

import Info from "@icons/Info";
import { Box, IconButton, Paper, Button, Typography, useMediaQuery, useTheme, Popover } from "@mui/material";

import ExpandLessIconBG from "@icons/ExpandLessIconBG";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import ShareNetwork from "@icons/ShareNetwork.svg";
import ArrowCounterClockWise from "@icons/ArrowCounterClockWise.svg";

type WhenVariants = {
  title: string;
  value: "before" | "after";
  id: string;
};

const whenValues: WhenVariants[] = [
  {
    title: "До формы контактов",
    value: "before",
    id: "before-contact-form",
  },
  {
    title: "После формы контактов",
    value: "after",
    id: "after-the-contact-form",
  },
];

interface Props {
  quizExpand: boolean;
}

const InfoView = () => {
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;

  return (
    <>
      <Info
        sx={{
          "MuiIconButton-root": {
            boxShadow: "0 0 10px 10px red",
          },
        }}
        onClick={handleClick}
      />
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left",
        }}
      >
        <Paper
          sx={{
            p: "20px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
          }}
        >
          <Typography>Oтправка письма с результатом респонденту после отображения на экране</Typography>
        </Paper>
      </Popover>
    </>
  );
};

export const WhenCard = ({ quizExpand }: Props) => {
  const quiz = useCurrentQuiz();
  const theme = useTheme();

  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1100));

  const [expand, setExpand] = useState(true);

  useEffect(() => {
    setExpand(true);
  }, [quizExpand]);

  return (
    <Paper
      data-cy="quiz-question-card"
      sx={{
        maxWidth: "796px",
        width: "100%",
        borderRadius: "12px",
        backgroundColor: expand ? "white" : "#EEE4FC",
        border: expand ? "none" : "1px solid #9A9AAF",
        boxShadow: "0px 10px 30px #e7e7e7",
        m: "20px 0",
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          padding: "20px",
          justifyContent: "space-between",
          minHeight: "40px",
        }}
      >
        <Typography
          sx={{
            margin: isMobile ? "10px 0" : 0,
            color: expand ? "#9A9AAF" : "#000000",
          }}
        >
          Показывать результат
        </Typography>
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-end",
            width: "auto",
            position: "relative",
          }}
        >
          <IconButton
            sx={{ padding: "0", margin: "5px" }}
            disableRipple
            data-cy="expand-question"
            onClick={() => setExpand(!expand)}
          >
            {expand ? (
              <ExpandLessIconBG />
            ) : (
              <ExpandLessIcon
                sx={{
                  boxSizing: "border-box",
                  fill: theme.palette.brightPurple.main,
                  background: "#FFF",
                  borderRadius: "6px",
                  height: "30px",
                  width: "30px",
                }}
              />
            )}
          </IconButton>
        </Box>
      </Box>
      {expand && quiz && (
        <>
          <Box
            sx={{
              p: "33px 20px",
            }}
          >
            <Box
              sx={{
                display: "flex",
                flexDirection: isSmallMonitor ? "column" : "row",
                justifyContent: "space-between",
                gap: "20px",
                mb: "20px",
              }}
            >
              {whenValues.map(({ title, value, id }, index) => (
                <Box
                  display="flex"
                  key={id}
                >
                  <Button
                    id={id}
                    onClick={() => {
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.resultInfo.showResultForm = value;
                        quiz.config;
                      });
                    }}
                    key={title}
                    sx={{
                      bgcolor: quiz?.config.resultInfo.showResultForm === value ? " #7E2AEA" : "#F2F3F7",
                      color: quiz?.config.resultInfo.showResultForm === value ? " white" : "#9A9AAF",
                      minWidth: isSmallMonitor ? (isMobile ? undefined : "310px") : "auto",
                      borderRadius: "8px",
                      width: isMobile ? "100%" : "220px",
                      height: "44px",
                      fontSize: "17px",
                      border: quiz?.config.resultInfo.showResultForm === value ? "none" : "1px solid #9A9AAF",
                      "&:hover": {
                        backgroundColor: quiz?.config.resultInfo.showResultForm === value ? "#581CA7" : "#7E2AEA",
                        color: "white",
                      },
                    }}
                  >
                    {title}
                  </Button>
                </Box>
              ))}
              <Box>
                <Button
                  onClick={() => {
                    updateQuiz(quiz.id, (quiz) => {
                      if (quiz.config.resultInfo.when) {
                        quiz.config.resultInfo.when = "";

                        return;
                      }
                      quiz.config.resultInfo.when = "email";
                    });

                    updateQuiz(quiz?.id, (quiz) => {
                      quiz.config.formContact.fields["email"].used = true;
                    });
                  }}
                  sx={{
                    bgcolor: quiz?.config.resultInfo.when === "email" ? " #7E2AEA" : "#F2F3F7",
                    color: quiz?.config.resultInfo.when === "email" ? " white" : "#9A9AAF",
                    minWidth: isSmallMonitor ? (isMobile ? undefined : "310px") : "auto",
                    borderRadius: "8px",
                    width: isMobile ? "100%" : "220px",
                    height: "44px",
                    fontSize: "17px",
                    border: quiz?.config.resultInfo.when === "email" ? "none" : "1px solid #9A9AAF",
                    "&:hover": {
                      backgroundColor: quiz?.config.resultInfo.when === "email" ? "#581CA7" : "#7E2AEA",
                      color: "white",
                    },
                  }}
                >
                  Отправить на E-mail
                </Button>
                <InfoView />
              </Box>
            </Box>
          </Box>
        </>
      )}
    </Paper>
  );
};
