import { Box, Link, Typography, useMediaQuery, useTheme } from "@mui/material";
import {
  clearQuestionImages,
  uploadQuestionImage,
} from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useMemo, useState } from "react";
import { EnterIcon } from "@/assets/icons/questionsPage/enterIcon";
import type { QuizQuestionVarImg } from "@frontend/squzanswerer/dist-package/model/questionTypes/varimg";

//@/model/questionTypes/images";
import { useAddAnswer } from "@/utils/hooks/useAddAnswer";
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 SwitchAnswerOptionsPict from "./switchOptionsPict";

import imge from "@/assets/card-1.png"
import { CropModalInit } from "@/ui_kit/Modal/CropModal";
interface Props {
  question: QuizQuestionVarImg;
  openBranchingPage: boolean;
  setOpenBranchingPage: (a: boolean) => void;
}

export default function OptionsPicture({
  question,
  openBranchingPage,
  setOpenBranchingPage,
}: Props) {
  const theme = useTheme();
  const {onClickAddAnAnswer} = useAddAnswer();
  const quizQid = useCurrentQuiz()?.qid;
  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 [switchState, setSwitchState] = useState("setting");
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  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);
  };

  return (
    <>
      <Box sx={{ padding: "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", gap: "10px" }}>
          <Link
            component="button"
            variant="body2"
            sx={{ color: theme.palette.brightPurple.main }}
            onClick={() => onClickAddAnAnswer(question)}
          >
            Добавьте ответ
          </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}
        questionType={question.type}
        questionHasParent={question.content.rule.parentId?.length !== 0}
        setOpenBranchingPage={setOpenBranchingPage}
      />
      <SwitchAnswerOptionsPict
        switchState={switchState}
        question={question}
      />
    </>
  );
}
