import { Box, Button, Collapse, Divider, Typography, useMediaQuery, useTheme } from "@mui/material";
import { useCurrentQuiz } from "@root/quizes/hooks";
import CircleColorPicker from "@ui_kit/CircleColorPicker";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
import PenaTextField from "@ui_kit/PenaTextField";
import { nanoid } from "nanoid";
import { ReactNode, useState } from "react";
import Dots from "@/assets/dots.png";
import WidgetScript from "../WidgetScript";
import { createContainerWidgetScriptText } from "../createWidgetScriptText";
import { useWidgetUrl } from "../useWidgetUrl";

interface Props {
  step: 2 | 3;
  nextButton: ReactNode;
}

export default function ContainerWidgetSetup({ step, nextButton }: Props) {
  const theme = useTheme();
  const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1065));
  const quiz = useCurrentQuiz();
  const widgetUrl = useWidgetUrl();
  const [isAutoopenQuizSettingsOpen, setIsAutoopenQuizSettingsOpen] = useState<boolean>(false);
  const [widgetWidth, setWidgetWidth] = useState<string>("");
  const [widgetHeight, setWidgetHeight] = useState<string>("");
  const [hideOnMobile, setHideOnMobile] = useState<boolean>(false);
  const [showButtonOnMobile, setShowButtonOnMobile] = useState<boolean>(false);
  const [rounded, setRounded] = useState<boolean>(false);
  const [withShadow, setWithShadow] = useState<boolean>(false);
  const [buttonFlash, setButtonFlash] = useState<boolean>(false);
  const [buttonText, setButtonText] = useState<string>("");
  const [buttonBackgroundColor, setButtonBackgroundColor] = useState<string>(theme.palette.brightPurple.main);
  const [buttonTextColor, setButtonTextColor] = useState<string>("#FFFFFF");
  const [autoShowQuiz, setAutoShowQuiz] = useState<boolean>(false);
  const [autoShowQuizTime, setAutoShowQuizTime] = useState<number>(10);
  const [openOnLeaveAttempt, setOpenOnLeaveAttempt] = useState<boolean>(false);

  if (!quiz) return null;

  if (step === 3) {
    const scriptText = createContainerWidgetScriptText(
      {
        quizId: quiz.qid,
        selector: `#pena-quiz-container-${nanoid(6)}`,
        dimensions:
          widgetWidth || widgetHeight
            ? {
                width: widgetWidth ? `${widgetWidth}px` : "100%",
                height: widgetHeight ? `${widgetHeight}px` : "100%",
              }
            : undefined,
        hideOnMobile: hideOnMobile || undefined,
        showButtonOnMobile: showButtonOnMobile || undefined,
        rounded: rounded || undefined,
        withShadow: withShadow || undefined,
        buttonFlash: buttonFlash || undefined,
        buttonText: buttonText || undefined,
        buttonBackgroundColor,
        buttonTextColor,
        autoShowQuizTime: autoShowQuiz ? autoShowQuizTime : undefined,
        openOnLeaveAttempt: openOnLeaveAttempt || undefined,
      },
      widgetUrl
    );

    return <WidgetScript scriptText={scriptText} helperText="Установите код в место, в котором должен быть квиз" />;
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: isSmallMonitor ? "column" : "row",
        alignItems: "start",
        gap: "40px",
        p: "20px",
      }}
    >
      <Box
        sx={{
          border: "1.5px solid #9A9AAF",
          borderRadius: "6px",
          flex: "1 1 0",
        }}
      >
        <Box
          sx={{
            background: theme.palette.background.default,
            borderBottom: "1.5px solid #9A9AAF",
            borderRadius: "6px 6px 0px 0px",
            minHeight: "34px",
            display: "flex",
            alignItems: "center",
            justifyContent: "end",
            paddingRight: "10px",
          }}
        >
          {" "}
          <img src={Dots} />
        </Box>
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            gap: "40px",
            height: "100%",
            p: "12%",
            pb: "7%",
          }}
        >
          <Box
            sx={{
              width: "100%",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              background: "#EEE4FC",
              borderRadius: "6px",
              border: "1px dashed #7E2AEA",
              p: "40px",
            }}
          >
            <Typography
              sx={{
                color: theme.palette.brightPurple.main,
                maxWidth: "365px",
              }}
            >
              Quiz будет открыт прямо в том месте, где вы установите код на сайте
            </Typography>
          </Box>
          <Typography sx={{ maxWidth: "414px", fontSize: "14px", alignSelf: "start" }}>
            В мобильной версии будет показана кнопка, открывающая quiz в модальном окне
          </Typography>
        </Box>
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: "15px",
          flex: "1 1 0",
        }}
      >
        <Typography fontWeight={500} color="#4D4D4D">
          1. Задайте размеры (опционально)
        </Typography>
        <Box sx={{ display: "flex", gap: "40px" }}>
          <Box sx={{ display: "flex", flexDirection: "column", gap: "20px" }}>
            <Typography sx={{ color: theme.palette.grey2.main }}>Ширина (px)</Typography>
            <PenaTextField
              type="number"
              value={widgetWidth}
              onChange={(e) => setWidgetWidth(e.target.value)}
              FormControlSx={{ maxWidth: "160px" }}
              placeholder="auto"
            />
          </Box>
          <Box sx={{ display: "flex", flexDirection: "column", gap: "20px" }}>
            <Typography sx={{ color: theme.palette.grey2.main }}>Высота (px)</Typography>
            <PenaTextField
              type="number"
              value={widgetHeight}
              onChange={(e) => setWidgetHeight(e.target.value)}
              FormControlSx={{ maxWidth: "160px" }}
              placeholder="auto"
            />
          </Box>
        </Box>
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: "15px",
            alignItems: "start",
          }}
        >
          <Typography fontWeight={500} color="#4D4D4D">
            2. Настройте кнопку для мобильной версии
          </Typography>
          <Box
            sx={{
              display: "flex",
              gap: "40px",
            }}
          >
            <Typography sx={{ color: theme.palette.grey2.main }}>Цвет кнопки</Typography>
            <CircleColorPicker color={buttonBackgroundColor} onChange={(color) => setButtonBackgroundColor(color)} />
            <Typography sx={{ color: theme.palette.grey2.main }}>Цвет текста кнопки</Typography>
            <CircleColorPicker color={buttonTextColor} onChange={(color) => setButtonTextColor(color)} />
          </Box>
          <CustomCheckbox
            label="Отключить на мобильных устройствах"
            checked={hideOnMobile}
            handleChange={(e) => setHideOnMobile(e.target.checked)}
          />
          <CustomCheckbox label="Закругленная" checked={rounded} handleChange={(e) => setRounded(e.target.checked)} />
          <CustomCheckbox label="С тенью" checked={withShadow} handleChange={(e) => setWithShadow(e.target.checked)} />
          <CustomCheckbox
            label="С бликом"
            checked={buttonFlash}
            handleChange={(e) => setButtonFlash(e.target.checked)}
          />
          <CustomCheckbox
            label="Кнопка на мобильной версии"
            checked={showButtonOnMobile}
            handleChange={(e) => setShowButtonOnMobile(e.target.checked)}
          />
          <Typography sx={{ color: theme.palette.grey2.main }}>Текст кнопки</Typography>
          <PenaTextField
            value={buttonText}
            onChange={(e) => setButtonText(e.target.value)}
            placeholder="Пройти тест"
            FormControlSx={{ maxWidth: "360px" }}
          />
          <Button
            variant="text"
            onClick={() => setIsAutoopenQuizSettingsOpen((p) => !p)}
            sx={{
              fontSize: "16px",
              lineHeight: "19px",
              color: theme.palette.brightPurple.main,
              textDecorationColor: theme.palette.brightPurple.main,
              textDecoration: "underline",
              textAlign: "left",
              px: 0,
            }}
          >
            + Автооткрытие quiz
          </Button>
          <Collapse in={isAutoopenQuizSettingsOpen}>
            <Box
              sx={{
                p: "20px",
                backgroundColor: "#F2F3F7",
                borderRadius: "8px",
              }}
            >
              <CustomCheckbox
                label="Автооткрытие квиза"
                checked={autoShowQuiz}
                handleChange={(e) => setAutoShowQuiz(e.target.checked)}
              />
              <CustomCheckbox
                label="Открывать квиз при попытке уйти с сайта"
                checked={openOnLeaveAttempt}
                handleChange={(e) => setOpenOnLeaveAttempt(e.target.checked)}
                sx={{
                  mt: "15px",
                }}
              />
              <Collapse in={autoShowQuiz}>
                <Box
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "15px",
                    pt: "15px",
                  }}
                >
                  <Divider color="#9A9AAF" />
                  <Box
                    sx={{
                      display: "flex",
                      gap: "10px",
                      alignItems: "center",
                    }}
                  >
                    <Typography sx={{ color: theme.palette.grey2.main }}>Показывать через</Typography>
                    <PenaTextField
                      type="number"
                      value={autoShowQuizTime}
                      onChange={(e) => setAutoShowQuizTime(parseInt(e.target.value))}
                      FormControlSx={{
                        width: "90px",
                      }}
                    />
                    <Typography sx={{ color: theme.palette.grey2.main }}>секунд</Typography>
                  </Box>
                </Box>
              </Collapse>
            </Box>
          </Collapse>
        </Box>
        <Box
          sx={{
            display: "flex",
            justifyContent: "end",
            pt: "10px",
          }}
        >
          {nextButton}
        </Box>
      </Box>
    </Box>
  );
}
