import { ButtonWidgetFixedParams, ButtonWidgetParams } from "@frontend/squzanswerer";
import {
  Box,
  Button,
  Collapse,
  Divider,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  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 RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";
import RunningStripe from "@ui_kit/RunningStripe";
import { nanoid } from "nanoid";
import { ReactNode, useState } from "react";
import Dots from "@/assets/dots.png";
import widgetPreviewImage from "@/assets/widget-preview.png";
import WidgetScript from "../../WidgetScript";
import { createButtonWidgetScriptText } from "../../createWidgetScriptText";
import { useWidgetUrl } from "../../useWidgetUrl";
import ButtonWidgetPreviewDesktop from "./ButtonWidgetPreviewDesktop";
import ButtonWidgetPreviewMobile from "./ButtonWidgetPreviewMobile";

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

export default function ButtonWidgetSetup({ step, nextButton }: Props) {
  const theme = useTheme();
  const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1065));
  const quiz = useCurrentQuiz();
  const widgetUrl = useWidgetUrl();
  const [widgetWidth, setWidgetWidth] = useState<string>("");
  const [widgetHeight, setWidgetHeight] = useState<string>("");
  const [isAutoopenQuizSettingsOpen, setIsAutoopenQuizSettingsOpen] = useState<boolean>(false);
  const [hideOnMobile, setHideOnMobile] = 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);
  const [fixedSide, setFixedSide] = useState<null | ButtonWidgetFixedParams["fixedSide"]>(null);
  const [fullScreen, setFullScreen] = useState<boolean>(false);

  if (!quiz) return null;

  if (step === 3) {
    const genericParams = {
      quizId: quiz.qid,
      fullScreen: fullScreen || undefined,
      dialogDimensions:
        !fullScreen && (widgetWidth || widgetHeight)
          ? {
              width: widgetWidth ? `${widgetWidth}px` : "100%",
              height: widgetHeight ? `${widgetHeight}px` : "100%",
            }
          : undefined,
      hideOnMobile: hideOnMobile || undefined,
      rounded: rounded || undefined,
      withShadow: withShadow || undefined,
      buttonFlash: buttonFlash || undefined,
      buttonText: buttonText || undefined,
      buttonBackgroundColor,
      buttonTextColor,
      autoShowQuizTime: autoShowQuiz ? autoShowQuizTime : undefined,
      openOnLeaveAttempt: openOnLeaveAttempt || undefined,
    };

    let params: ButtonWidgetParams | ButtonWidgetFixedParams;
    if (fixedSide === null) {
      params = {
        ...genericParams,
        selector: `#pena-quiz-button-container-${nanoid(6)}`,
      };
    } else {
      params = {
        ...genericParams,
        fixedSide,
      };
    }

    const scriptText = createButtonWidgetScriptText(params, widgetUrl);

    return (
      <WidgetScript
        scriptText={scriptText}
        helperText={
          fixedSide === null
            ? "Установите код в место, в котором должна быть кнопка"
            : "Установите код внутрь тэга head"
        }
      />
    );
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: isSmallMonitor ? "column" : "row",
        gap: "40px",
        p: "20px",
      }}
    >
      <Box
        sx={{
          flex: "1 1 0",
        }}
      >
        {fixedSide === null ? (
          <Box
            sx={{
              border: "1.5px solid #9A9AAF",
              borderRadius: "6px",
              height: "364px",
              display: "flex",
              flexDirection: "column",
            }}
          >
            <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",
                justifyContent: "center",
                alignItems: "center",
                flexGrow: 1,
              }}
            >
              <Button
                variant="contained"
                disableFocusRipple
                sx={{
                  overflow: "hidden",
                  py: "23px",
                  px: "40px",
                  fontSize: "20px",
                  color: buttonTextColor,
                  backgroundColor: buttonBackgroundColor,
                  boxShadow: withShadow
                    ? "2px 5px 20px 2px rgba(25, 6, 50, 0.4), 0 2px 10px 0 rgba(35, 17, 58, 0.1)"
                    : "none",
                  borderRadius: rounded ? "30px" : "0px",
                  transition: "all 0.3s ease",
                }}
              >
                {buttonText || "Пройти тест"}
                {buttonFlash && <RunningStripe />}
              </Button>
            </Box>
          </Box>
        ) : (
          <Box
            sx={{
              p: "20px",
              pt: "40px",
            }}
          >
            <Box
              sx={{
                position: "relative",
              }}
            >
              <img
                src={widgetPreviewImage}
                style={{
                  display: "block",
                  width: "100%",
                  height: "100%",
                }}
              />
              <Box
                sx={{
                  position: "absolute",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  containerType: "size",
                }}
              >
                <ButtonWidgetPreviewDesktop
                  fixedSide={fixedSide}
                  buttonBackgroundColor={buttonBackgroundColor}
                  buttonTextColor={buttonTextColor}
                  buttonFlash={buttonFlash}
                  buttonText={buttonText}
                  rounded={rounded}
                  withShadow={withShadow}
                />
                {!hideOnMobile && (
                  <ButtonWidgetPreviewMobile
                    fixedSide={fixedSide}
                    buttonBackgroundColor={buttonBackgroundColor}
                    buttonTextColor={buttonTextColor}
                  />
                )}
              </Box>
            </Box>
          </Box>
        )}
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: "15px",
          flex: "1 1 0",
        }}
      >
        <Typography
          fontWeight={500}
          color="#4D4D4D"
        >
          1. Задайте размеры окна квиза (опционально)
        </Typography>
        <CustomCheckbox
          label="Квиз на весь экран"
          checked={fullScreen}
          handleChange={(e) => setFullScreen(e.target.checked)}
        />
        <Collapse in={!fullScreen}>
          <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>
        </Collapse>
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: "15px",
            alignItems: "start",
          }}
        >
          <Typography
            fontWeight={500}
            color="#4D4D4D"
          >
            2. Конструктор кнопки
          </Typography>
          <Box
            sx={{
              display: "flex",
              gap: "40px",
              alignItems: "center",
            }}
          >
            <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={fixedSide !== null}
            handleChange={(e) => setFixedSide(e.target.checked ? "left" : null)}
          />
          <Collapse in={fixedSide !== null}>
            <FormControl>
              <RadioGroup
                sx={{
                  flexDirection: "row",
                  gap: "24px",
                  pl: "40px",
                }}
                value={fixedSide}
                onChange={(e) => {
                  setFixedSide(e.target.value as ButtonWidgetFixedParams["fixedSide"]);
                }}
              >
                <FormControlLabel
                  value="left"
                  control={
                    <Radio
                      checkedIcon={<RadioCheck />}
                      icon={<RadioIcon />}
                    />
                  }
                  label="Слева"
                  sx={{
                    color: theme.palette.grey2.main,
                  }}
                />
                <FormControlLabel
                  value="right"
                  control={
                    <Radio
                      checkedIcon={<RadioCheck />}
                      icon={<RadioIcon />}
                    />
                  }
                  label="Справа"
                  sx={{
                    color: theme.palette.grey2.main,
                  }}
                />
              </RadioGroup>
            </FormControl>
          </Collapse>
          <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>
  );
}
