import { Box, Link, Typography, useMediaQuery, useTheme } from "@mui/material";
import {
  addQuestionVariant,
  clearQuestionImages,
  uploadQuestionImage,
} from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { CropModal, useCropModalState } from "@ui_kit/Modal/CropModal";
import { useEffect, useState } from "react";
import { EnterIcon } from "../../../assets/icons/questionsPage/enterIcon";
import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";
import { useDisclosure } from "../../../utils/useDisclosure";
import { AnswerDraggableList } from "../AnswerDraggableList";
import ImageEditAnswerItem from "../AnswerDraggableList/ImageEditAnswerItem";
import ButtonsOptionsAndPict from "../ButtonsOptionsAndPict";
import { UploadImageModal } from "../UploadImage/UploadImageModal";
import SwitchOptionsAndPict from "./switchOptionsAndPict";

interface Props {
  question: QuizQuestionVarImg;
  openBranchingPage: boolean;
  setOpenBranchingPage: (a: boolean) => void;
}

export default function OptionsAndPicture({
  question,
  setOpenBranchingPage,
}: Props) {
  const [switchState, setSwitchState] = useState("setting");
  const [pictureUploding, setPictureUploading] = useState<boolean>(false);
  const [selectedVariantId, setSelectedVariantId] = useState<string | null>(
    null,
  );
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const quizQid = useCurrentQuiz()?.qid;
  const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] =
    useDisclosure();
  const {
    isCropModalOpen,
    openCropModal,
    closeCropModal,
    imageBlob,
    originalImageUrl,
    setCropModalImageBlob,
  } = useCropModalState();

  const handleImageUpload = async (file: File) => {
    if (!selectedVariantId) return;

    setPictureUploading(true);

    const url = await uploadQuestionImage(
      question.id,
      quizQid,
      file,
      (question, url) => {
        if (!("variants" in question.content)) return;

        const variant = question.content.variants.find(
          (variant) => variant.id === selectedVariantId,
        );
        if (!variant) return;

        variant.extendedText = url;
        variant.originalImageUrl = url;
      },
    );
    closeImageUploadModal();
    openCropModal(file, url);

    setPictureUploading(false);
  };

  function handleCropModalSaveClick(imageBlob: Blob) {
    if (!selectedVariantId) return;

    uploadQuestionImage(question.id, quizQid, imageBlob, (question, url) => {
      if (!("variants" in question.content)) return;

      const variant = question.content.variants.find(
        (variant) => variant.id === selectedVariantId,
      );
      if (!variant) return;

      variant.extendedText = url;
    });
  }

  useEffect(() => {
    if (question.deleteTimeoutId) {
      clearTimeout(question.deleteTimeoutId);
    }
  }, [question]);

  return (
    <>
      <Box sx={{ pl: "20px", pr: "20px" }}>
        <AnswerDraggableList
          questionId={question.id}
          variants={question.content.variants.map((variant, index) => (
            <ImageEditAnswerItem
              key={variant.id}
              index={index}
              disableKeyDown={question.content.variants.length >= 100}
              questionId={question.id}
              largeCheck={question.content.largeCheck}
              variant={variant}
              isMobile={isMobile}
              openCropModal={openCropModal}
              openImageUploadModal={openImageUploadModal}
              pictureUploding={pictureUploding}
              setSelectedVariantId={setSelectedVariantId}
            />
          ))}
        />
        <UploadImageModal
          isOpen={isImageUploadOpen}
          onClose={closeImageUploadModal}
          handleImageChange={handleImageUpload}
        />
        <CropModal
          isOpen={isCropModalOpen}
          imageBlob={imageBlob}
          originalImageUrl={originalImageUrl}
          setCropModalImageBlob={setCropModalImageBlob}
          onClose={closeCropModal}
          onSaveImageClick={handleCropModalSaveClick}
          onDeleteClick={() => {
            if (selectedVariantId)
              clearQuestionImages(question.id, selectedVariantId);
          }}
          cropAspectRatio={{ width: 452, height: 300 }}
        />
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            marginBottom: "17px",
          }}
        >
          <Link
            component="button"
            variant="body2"
            sx={{
              color: theme.palette.brightPurple.main,
              fontWeight: "400",
              fontSize: "16px",
              mr: "4px",
              height: "19px",
            }}
            onClick={() => {
              addQuestionVariant(question.id);
            }}
          >
            Добавьте ответ
          </Link>
          {isMobile ? null : (
            <>
              <Typography
                sx={{
                  fontWeight: 400,
                  lineHeight: "21.33px",
                  color: theme.palette.grey2.main,
                  fontSize: "16px",
                }}
              >
                или нажмите Enter
              </Typography>
              <EnterIcon
                style={{
                  color: "#7E2AEA",
                  fontSize: "24px",
                  marginLeft: "6px",
                }}
              />
            </>
          )}
        </Box>
      </Box>
      <ButtonsOptionsAndPict
        switchState={switchState}
        SSHC={setSwitchState}
        questionId={question.id}
        questionContentId={question.content.id}
        questionHasParent={question.content.rule.parentId.length !== 0}
        questionType={question.type}
        openBranchingPage={false}
        setOpenBranchingPage={setOpenBranchingPage}
      />
      <SwitchOptionsAndPict switchState={switchState} question={question} />
    </>
  );
}
