import { BannerWidgetParams } 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 { ReactNode, useState } from "react";
import widgetPreviewImage from "@/assets/widget-preview.png";
import WidgetScript from "../../WidgetScript";
import { createBannerWidgetScriptText } from "../../createWidgetScriptText";
import { useWidgetUrl } from "../../useWidgetUrl";
import BannerWidgetPreviewDesktop from "./BannerWidgetPreviewDesktop";
import BannerWidgetPreviewMobile from "./BannerWidgetPreviewMobile";

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

export default function BannerWidgetSetup({ 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 [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 [position, setPosition] = useState<BannerWidgetParams["position"]>("topleft");
  const [bannerFullWidth, setBannerFullWidth] = useState<boolean>(false);
  const [autoShowWidgetTime, setAutoShowWidgetTime] = useState<number>(10);
  const [appealText, setAppealText] = useState<string>("");
  const [quizHeaderText, setQuizHeaderText] = useState<string>("");
  const [pulsation, setPulsation] = useState<boolean>(false);
  const [fullScreen, setFullScreen] = useState<boolean>(false);

  if (!quiz) return null;

  if (step === 3) {
    const scriptText = createBannerWidgetScriptText(
      {
        quizId: quiz.qid,
        position,
        hideOnMobile: hideOnMobile || undefined,
        rounded: bannerFullWidth ? undefined : rounded || undefined,
        withShadow: withShadow || undefined,
        buttonFlash: buttonFlash || undefined,
        buttonBackgroundColor,
        buttonTextColor,
        autoShowQuizTime: autoShowQuiz ? autoShowQuizTime : undefined,
        openOnLeaveAttempt: openOnLeaveAttempt || undefined,
        bannerFullWidth: bannerFullWidth || undefined,
        autoShowWidgetTime,
        appealText: appealText || undefined,
        quizHeaderText: quizHeaderText || undefined,
        pulsation: pulsation || undefined,
        fullScreen: fullScreen || undefined,
        dialogDimensions:
          !fullScreen && (widgetWidth || widgetHeight)
            ? {
                width: widgetWidth ? `${widgetWidth}px` : "100%",
                height: widgetHeight ? `${widgetHeight}px` : "100%",
              }
            : undefined,
      },
      widgetUrl
    );

    return (
      <WidgetScript
        scriptText={scriptText}
        helperText="Установите код внутрь тэга head"
      />
    );
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: isSmallMonitor ? "column" : "row",
        gap: "40px",
        p: "20px",
      }}
    >
      <Box
        sx={{
          flex: "1 1 0",
          p: "20px",
          pt: "40px",
        }}
      >
        <Box
          sx={{
            position: "relative",
          }}
        >
          <img
            src={widgetPreviewImage}
            style={{
              display: "block",
              width: "100%",
              height: "100%",
            }}
          />
          <BannerWidgetPreviewDesktop
            appealText={appealText}
            quizHeaderText={quizHeaderText}
            position={position}
            pulsation={pulsation}
            withShadow={withShadow}
            buttonFlash={buttonFlash}
            bannerFullWidth={bannerFullWidth}
            buttonBackgroundColor={buttonBackgroundColor}
            buttonTextColor={buttonTextColor}
            rounded={rounded}
          />
          <BannerWidgetPreviewMobile
            appealText={appealText}
            quizHeaderText={quizHeaderText}
            position={position}
            pulsation={pulsation}
            withShadow={withShadow}
            buttonFlash={buttonFlash}
            buttonBackgroundColor={buttonBackgroundColor}
            buttonTextColor={buttonTextColor}
          />
        </Box>
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: "15px",
          flex: "1 1 0",
        }}
      >
        <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>
        <Typography sx={{ color: theme.palette.grey2.main }}>Текст-призыв</Typography>
        <PenaTextField
          placeholder="Пройти тест"
          value={appealText}
          onChange={(e) => setAppealText(e.target.value)}
          FormControlSx={{ maxWidth: "360px" }}
        />
        <Typography sx={{ color: theme.palette.grey2.main }}>Заголовок quiz</Typography>
        <PenaTextField
          placeholder="Заголовок quiz"
          value={quizHeaderText}
          onChange={(e) => setQuizHeaderText(e.target.value)}
          FormControlSx={{ maxWidth: "360px" }}
        />
        <Box
          sx={{
            display: "flex",
            gap: "10px",
            alignItems: "center",
          }}
        >
          <Typography sx={{ color: theme.palette.grey2.main }}>Показывать через</Typography>
          <PenaTextField
            type="number"
            value={autoShowWidgetTime}
            onChange={(e) => setAutoShowWidgetTime(parseInt(e.target.value))}
            FormControlSx={{
              width: "90px",
            }}
          />
          <Typography sx={{ color: theme.palette.grey2.main }}>секунд</Typography>
        </Box>
        <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={bannerFullWidth}
          handleChange={(e) => {
            setBannerFullWidth(e.target.checked);
            if (e.target.checked) setPosition("topleft");
          }}
        />
        <Typography sx={{ color: theme.palette.grey2.main }}>Расположение</Typography>
        <FormControl>
          <RadioGroup
            value={position}
            onChange={(e) => {
              setPosition(e.target.value as BannerWidgetParams["position"]);
            }}
            sx={{
              display: "flex",
              flexWrap: "wrap",
              flexDirection: "row",
              paddingLeft: "5px",
              justifyContent: "space-between",
            }}
          >
            {bannerFullWidth ? (
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "row",
                  gap: "24px",
                }}
              >
                <FormControlLabel
                  label="Сверху страницы"
                  value="topleft"
                  control={
                    <Radio
                      checkedIcon={<RadioCheck />}
                      icon={<RadioIcon />}
                    />
                  }
                  sx={{ color: theme.palette.grey2.main }}
                />
                <FormControlLabel
                  label="Снизу страницы"
                  value="bottomleft"
                  control={
                    <Radio
                      checkedIcon={<RadioCheck />}
                      icon={<RadioIcon />}
                    />
                  }
                  sx={{ color: theme.palette.grey2.main }}
                />
              </Box>
            ) : (
              <>
                <Box
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <FormControlLabel
                    label="Слева сверху"
                    value="topleft"
                    control={
                      <Radio
                        checkedIcon={<RadioCheck />}
                        icon={<RadioIcon />}
                      />
                    }
                    sx={{ color: theme.palette.grey2.main }}
                  />
                  <FormControlLabel
                    label="Слева снизу"
                    value="bottomleft"
                    control={
                      <Radio
                        checkedIcon={<RadioCheck />}
                        icon={<RadioIcon />}
                      />
                    }
                    sx={{ color: theme.palette.grey2.main }}
                  />
                </Box>
                <Box
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <FormControlLabel
                    label="Справа сверху"
                    value="topright"
                    control={
                      <Radio
                        checkedIcon={<RadioCheck />}
                        icon={<RadioIcon />}
                      />
                    }
                    sx={{ color: theme.palette.grey2.main }}
                  />
                  <FormControlLabel
                    label="Справа снизу"
                    value="bottomright"
                    control={
                      <Radio
                        checkedIcon={<RadioCheck />}
                        icon={<RadioIcon />}
                      />
                    }
                    sx={{ color: theme.palette.grey2.main }}
                  />
                </Box>
              </>
            )}
          </RadioGroup>
        </FormControl>
        <Typography sx={{ color: theme.palette.grey2.main }}>Параметры</Typography>
        {!bannerFullWidth && (
          <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={pulsation}
          handleChange={(e) => setPulsation(e.target.checked)}
        />
        <CustomCheckbox
          label="Отключить на мобильных устройствах"
          checked={hideOnMobile}
          handleChange={(e) => setHideOnMobile(e.target.checked)}
        />
        <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",
            alignSelf: "start",
            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
          sx={{
            display: "flex",
            justifyContent: "end",
            pt: "10px",
          }}
        >
          {nextButton}
        </Box>
      </Box>
    </Box>
  );
}
