import { useState } from "react";
import { Typography, Box, useTheme, ButtonBase } from "@mui/material";
import UploadBox from "@ui_kit/UploadBox";
import { CroppingModal } from "@ui_kit/Modal/CroppingModal";
import UploadIcon from "../../../assets/icons/UploadIcon";
import * as React from "react";
import { questionStore, updateQuestionsList } from "@root/questions";
import { UploadImageModal } from "./UploadImageModal";

import type { DragEvent } from "react";

type UploadImageProps = {
  totalIndex: number;
};

export default function UploadImage({ totalIndex }: UploadImageProps) {
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  const { listQuestions } = questionStore();

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  const imgHC = (files: FileList | null) => {
    if (files?.length) {
      const [file] = Array.from(files);

      let clonContent = listQuestions[totalIndex].content;
      clonContent.back = URL.createObjectURL(file);
      updateQuestionsList(totalIndex, { content: clonContent });

      handleClose();
      setOpened(true);
    }
  };
  const [opened, setOpened] = useState<boolean>(false);

  const handleDrop = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    event.stopPropagation();

    imgHC(event.dataTransfer.files);
  };

  return (
    <Box sx={{ padding: "20px" }}>
      <Typography
        sx={{
          fontWeight: 500,
          color: theme.palette.grey3.main,
          mt: "11px",
          mb: "14px",
        }}
      >
        Загрузить изображение
      </Typography>
      <ButtonBase
        onClick={handleOpen}
        sx={{ width: "100%", maxWidth: "260px" }}
      >
        <UploadBox
          handleDrop={handleDrop}
          sx={{ maxWidth: "260px" }}
          icon={<UploadIcon />}
          text="5 MB максимум"
        />
      </ButtonBase>
      <UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
      <CroppingModal
        opened={opened}
        onClose={() => setOpened(false)}
        picture={listQuestions[totalIndex].content.back}
      />
    </Box>
  );
}
