import { SideWidgetParams } from "@frontend/squzanswerer";
import { Box, Collapse, 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 { ReactNode, useState } from "react";
import widgetPreviewImage from "@/assets/widget-preview.png";
import WidgetScript from "../../WidgetScript";
import { createSideWidgetScriptText } from "../../createWidgetScriptText";
import { useWidgetUrl } from "../../useWidgetUrl";
import SideWidgetPositionButton from "./SideWidgetPositionButton";
import SideWidgetPreviewDesktop from "./SideWidgetPreviewDesktop";
import SideWidgetPreviewMobile from "./SideWidgetPreviewMobile";
import CustomTextField from "@ui_kit/CustomTextField";

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

export default function SideWidgetSetup({ 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 [hideOnMobile, setHideOnMobile] = useState<boolean>(false);
  const [autoShowQuiz, setAutoShowQuiz] = useState<boolean>(false);
  const [autoShowQuizTime, setAutoShowQuizTime] = useState<number>(10);
  const [autoShowWidgetTime, setAutoShowWidgetTime] = useState<number>(10);
  const [position, setPosition] = useState<SideWidgetParams["position"]>("left");
  const [buttonText, setButtonText] = useState<string>("Пройти квиз");
  const [fullScreen, setFullScreen] = useState<boolean>(false);
  const [buttonFlash, setButtonFlash] = useState<boolean>(false);
  const [buttonBackgroundColor, setButtonBackgroundColor] = useState<string>(theme.palette.brightPurple.main);
  const [buttonTextColor, setButtonTextColor] = useState<string>("#FFFFFF");

  if (!quiz) return null;

  if (step === 3) {
    const scriptText = createSideWidgetScriptText(
      {
        quizId: quiz.qid,
        position: position,
        hideOnMobile: hideOnMobile || undefined,
        autoShowQuizTime: autoShowQuiz ? autoShowQuizTime : undefined,
        autoShowWidgetTime: autoShowWidgetTime || undefined,
        fullScreen: fullScreen || undefined,
        buttonFlash: buttonFlash || undefined,
        buttonTextColor,
        buttonText: buttonText,
        buttonBackgroundColor,
        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%",
            }}
          />
          <SideWidgetPreviewDesktop
            position={position}
            buttonFlash={buttonFlash}
            text={buttonText}
          />
          <SideWidgetPreviewMobile buttonFlash={buttonFlash} />
        </Box>
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: "15px",
          flex: "1 1 0",
        }}
      >
        <Typography color={theme.palette.grey2.main}>Расположение</Typography>
        <Box
          sx={{
            display: "flex",
            gap: "40px",
          }}
        >
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              gap: "14px",
              flex: "1 0 0",
            }}
          >
            <SideWidgetPositionButton
              isSelected={position === "left"}
              position="left"
              onClick={() => setPosition("left")}
            />
            <Typography color={theme.palette.grey2.main}>Слева снизу</Typography>
          </Box>
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              gap: "14px",
              flex: "1 0 0",
            }}
          >
            <SideWidgetPositionButton
              isSelected={position === "right"}
              position="right"
              onClick={() => setPosition("right")}
            />
            <Typography color={theme.palette.grey2.main}>Справа снизу</Typography>
          </Box>
        </Box>
        <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",
            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>
        <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>
        <CustomCheckbox
          label="С бликом"
          checked={buttonFlash}
          handleChange={(e) => setButtonFlash(e.target.checked)}
        />
        <Box>
          <CustomCheckbox
            label="Автооткрытие виджета при входе на сайт"
            checked={autoShowQuiz}
            handleChange={(e) => setAutoShowQuiz(e.target.checked)}
          />
          <Collapse in={autoShowQuiz}>
            <Box
              sx={{
                display: "flex",
                gap: "10px",
                alignItems: "center",
                mt: "14px",
              }}
            >
              <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>
            <Typography
              sx={{
                color: theme.palette.grey2.main,
                fontSize: "14px",
                mt: "8px",
              }}
            >
              Время, через которое квиз автоматически откроется
            </Typography>
          </Collapse>
        </Box>
        <Typography sx={{ color: theme.palette.grey2.main }}>Текст кнопки</Typography>
        <CustomTextField
          id="headingInput"
          onChange={(e) => setButtonText(e.target.value)}
          placeholder="Пройти тест"
          value={buttonText}
          sx={{
            borderColor: theme.palette.brightPurple.main,
          }}
          sxForm={{
            maxWidth: "360px",

          }}
          maxLength={17}
        />
        <Box
          sx={{
            display: "flex",
            justifyContent: "end",
            pt: "10px",
          }}
        >
          {nextButton}
        </Box>
      </Box>
    </Box>
  );
}
