import { VideofileIcon } from "@icons/questionsPage/VideofileIcon";
import { Box, Button, Typography, useMediaQuery, useTheme } from "@mui/material";
import { updateQuestion, uploadQuestionImage } from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import CustomTextField from "@ui_kit/CustomTextField";
import { CropModal, useCropModalState } from "@ui_kit/Modal/CropModal";
import { useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import type { QuizQuestionPage } from "../../../model/questionTypes/page";
import ButtonsOptions from "../ButtonsOptions";
import { UploadImageModal } from "../UploadImage/UploadImageModal";
import { UploadVideoModal } from "../UploadVideoModal";
import SwitchPageOptions from "./switchPageOptions";
import { useDisclosure } from "../../../utils/useDisclosure";

type Props = {
  disableInput?: boolean;
  question: QuizQuestionPage;
};

export default function PageOptions({ disableInput, question }: Props) {
  const [openVideoModal, setOpenVideoModal] = useState<boolean>(false);
  const [switchState, setSwitchState] = useState("setting");
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(980));
  const isFigmaTablet = useMediaQuery(theme.breakpoints.down(990));
  const isMobile = useMediaQuery(theme.breakpoints.down(780));
  const quizQid = useCurrentQuiz()?.qid;
  const { isCropModalOpen, openCropModal, closeCropModal, imageBlob, originalImageUrl, setCropModalImageBlob } =
    useCropModalState();
  const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] = useDisclosure();

  const setText = useDebouncedCallback((value) => {
    updateQuestion(question.id, (question) => {
      if (question.type !== "page") return;

      question.content.text = value;
    });
  }, 200);

  const SSHC = (data: string) => {
    setSwitchState(data);
  };

  async function handleImageUpload(file: File) {
    const url = await uploadQuestionImage(question.id, quizQid, file, (question, url) => {
      if (question.type !== "page") return;

      question.content.picture = url;
      question.content.originalPicture = url;
    });
    closeImageUploadModal();
    openCropModal(file, url);
  }

  function handleCropModalSaveClick(imageBlob: Blob) {
    uploadQuestionImage(question.id, quizQid, imageBlob, (question, url) => {
      if (question.type !== "page") return;

      question.content.picture = url;
    });
  }

  console.log(question.content.useImage);

  return (
    <>
      <Box
        sx={{
          width: isTablet ? "auto" : "100%",
          maxWidth: isFigmaTablet ? "549px" : "640px",
          display: "flex",
          px: "20px",
          flexDirection: "column",
          gap: isMobile ? "25px" : "20px",
        }}
      >
        <Box sx={{ display: disableInput ? "none" : "", mt: isMobile ? "15px" : "0px" }}>
          <CustomTextField
            placeholder={"Можно добавить текст"}
            text={question.content.text}
            onChange={({ target }) => setText(target.value)}
          />
        </Box>

        <Box
          sx={{
            mb: "20px",
            ml: isTablet ? "0px" : "60px",
            display: "flex",
            alignItems: "center",
            gap: "28px",
            justifyContent: isMobile ? "space-between" : null,
          }}
        >
          <Box
            sx={{
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: "20px",
            }}
          >
            <AddOrEditImageButton
              imageSrc={question.content.picture}
              onImageClick={() => {
                if (question.content.picture) {
                  return openCropModal(question.content.picture, question.content.originalPicture);
                }

                openImageUploadModal();
              }}
              onPlusClick={() => {
                openImageUploadModal();
              }}
            />

            <Typography
              sx={{
                display: isMobile ? "none" : "block",
                fontWeight: 400,
                fontSize: "16px",
                lineHeight: "18.96px",
                color: question.content.useImage ? "#7E2AEA" : "#9A9AAF",
              }}
              onClick={() =>
                updateQuestion(question.id, (question) => ((question as QuizQuestionPage).content.useImage = true))
              }
            >
              Изображение
            </Typography>
          </Box>
          <UploadImageModal
            isOpen={isImageUploadOpen}
            onClose={closeImageUploadModal}
            handleImageChange={handleImageUpload}
          />
          <CropModal
            isOpen={isCropModalOpen}
            imageBlob={imageBlob}
            originalImageUrl={originalImageUrl}
            setCropModalImageBlob={setCropModalImageBlob}
            onClose={closeCropModal}
            onSaveImageClick={handleCropModalSaveClick}
          />
          <Typography> или</Typography>
          <Box
            sx={{
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: "10px",
            }}
          >
            {isMobile ? (
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  width: "120px",
                  position: "relative",
                }}
              >
                <Box
                  sx={{
                    width: "100%",
                    background: "#EEE4FC",
                    height: "40px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    borderTopLeftRadius: "4px",
                    borderBottomLeftRadius: "4px",
                  }}
                >
                  <VideofileIcon
                    style={{
                      color: "#7E2AEA",
                      fontSize: "20px",
                    }}
                  />
                </Box>
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    width: "20px",
                    background: "#EEE4FC",
                    height: "40px",
                    color: "white",
                    backgroundColor: "#7E2AEA",
                    borderTopRightRadius: "4px",
                    borderBottomRightRadius: "4px",
                  }}
                >
                  +
                </Box>
              </Box>
            ) : (
              <Box
                sx={{
                  width: "60px",
                  height: "40px",
                  background: "#EEE4FC",
                  display: "flex",
                  justifyContent: "space-between",
                }}
              >
                <Box sx={{ display: "flex", alignItems: "center", justifyContent: "center", width: "100%" }}>
                  <VideofileIcon fontSize="22px" color="#7E2AEA" />
                </Box>
                <span
                  onClick={() => setOpenVideoModal(true)}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: "#7E2AEA",
                    height: "100%",
                    width: "25px",
                    color: "white",
                    fontSize: "15px",
                  }}
                >
                  +
                </span>
              </Box>
            )}

            <Typography
              sx={{
                display: isMobile ? "none" : "block",
                fontWeight: 400,
                fontSize: "16px",
                lineHeight: "18.96px",
                color: question.content.useImage ? "#9A9AAF" : "#7E2AEA",
              }}
              onClick={() =>
                updateQuestion(question.id, (question) => ((question as QuizQuestionPage).content.useImage = false))
              }
            >
              Видео
            </Typography>
          </Box>
          <UploadVideoModal
            open={openVideoModal}
            onClose={() => setOpenVideoModal(false)}
            video={question.content.video}
            onUpload={(url) => {
              updateQuestion(question.id, (question) => {
                if (question.type !== "page") return;

                question.content.video = url;
              });
            }}
          />
        </Box>
      </Box>
      <ButtonsOptions switchState={switchState} SSHC={SSHC} question={question} />
      <SwitchPageOptions switchState={switchState} question={question} />
    </>
  );
}
