import { AnyTypedQuizQuestion } from "@frontend/squzanswerer";
import { Box, Skeleton, Typography, useTheme } from "@mui/material";
import { updateQuestion, uploadQuestionImage } from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useState } from "react";
import { DropZone } from "../../../pages/startPage/dropZone";
import { CropModalInit } from "@/ui_kit/Modal/CropModal";

type UploadImageProps = {
  question: AnyTypedQuizQuestion;
  cropAspectRatio: {
    width: number;
    height: number;
  };
};

export default function UploadImage({ question, cropAspectRatio }: UploadImageProps) {
  const [pictureUploding, setPictureUploading] = useState<boolean>(false);
  const [openCropModal, setOpenCropModal] = useState(false);

  const theme = useTheme();
  const quiz = useCurrentQuiz();

  if (!quiz) return null;

  return (
    <Box sx={{ padding: "20px" }}>
      <Typography
        sx={{
          fontWeight: 500,
          color: theme.palette.grey3.main,
          mt: "11px",
          mb: "14px",
        }}
      >
        Загрузить изображение
      </Typography>
      {pictureUploding ? (
        <Skeleton variant="rounded" sx={{ height: "120px", width: "300px" }} />
      ) : (
        <DropZone
          text={"5 MB максимум"}
          sx={{ maxWidth: "300px", width: "100%" }}
          cropAspectRatio={cropAspectRatio}
          imageUrl={question.content.originalBack}
          originalImageUrl={question.content.originalBack}
          onImageUploadClick={async (file) => {
            setPictureUploading(true);

            await uploadQuestionImage(
              question.id,
              quiz.qid,
              file,
              (question, url) => {
                question.content.back = url;
                question.content.originalBack = url;
              },
            );

            setOpenCropModal(true)
            setPictureUploading(false);
          }
          }
          onDeleteClick={() => {
            updateQuestion(question.id, (question) => {
              question.content.back = null;
              question.content.originalBack = null;
              if ("editedUrlImagesList" in question.content) question.content.editedUrlImagesList = null;
            });
          }}
          onImageSavedClick={() => {
            setOpenCropModal(true)
          }}
        />
      )}
      <CropModalInit
        originalImageUrl={question.content.originalBack}
        editedUrlImagesList={question.content?.editedUrlImagesList}
        questionId={question.id.toString()}
        questionType={question.type}
        quizId={quiz.qid}
        open={openCropModal}
        selfClose={() => setOpenCropModal(false)}
        setPictureUploading={setPictureUploading}
      />
    </Box>
  );
}
