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

import imge from "@/assets/card-1.png"

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 [openCropModal, setOpenCropModal] = useState(false);
  
  const [selectedVariantId, setSelectedVariantId] = useState<string | null>(
    null,
  );
  const variant = question.content.variants.find(
    (variant) => variant.id === selectedVariantId,
  )
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const quizQid = useCurrentQuiz()?.qid;
  const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] = useDisclosure();

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

    setPictureUploading(true);

    closeImageUploadModal();
    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;
      },
    );
    setOpenCropModal(true)

    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={() => {setOpenCropModal(true)}}
              openImageUploadModal={openImageUploadModal}
              pictureUploding={pictureUploding}
              setSelectedVariantId={setSelectedVariantId}
              isOwn={Boolean(variant?.isOwn)}
              ownPlaceholder={question.content.ownPlaceholder}
            />
          ))}
        />
        <UploadImageModal
          isOpen={isImageUploadOpen}
          onClose={closeImageUploadModal}
          handleImageChange={handleImageUpload}
        />
        <CropModalInit
          originalImageUrl={variant?.originalImageUrl}
          editedUrlImagesList={variant?.editedUrlImagesList}
          questionId={question.id.toString()}
          questionType={question.type}
          quizId={quizQid}
          variantId={variant?.id}
          open={openCropModal}
          selfClose={() => setOpenCropModal(false)}
          setPictureUploading={setPictureUploading}
        />
        <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>
      <ButtonsOptions
        switchState={switchState}
        setSwitchState={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}
      />
    </>
  );
}
