import {Box, Typography, ButtonBase, useTheme, IconButton} from "@mui/material";
import { useQuizViewStore, updateAnswer } from "@root/quizView";
import { UPLOAD_FILE_TYPES_MAP } from "@ui_kit/QuizPreview/QuizPreviewQuestionTypes/File";

import UploadIcon from "@icons/UploadIcon";
import X from "@icons/CloseBold";
import type { ChangeEvent } from "react";
import type { QuizQuestionFile } from "../../../model/questionTypes/file";
import {DragEvent} from "react";

type FileProps = {
  currentQuestion: QuizQuestionFile;
};

export const File = ({ currentQuestion }: FileProps) => {
  const { answers } = useQuizViewStore();
  const answer = answers.find(
    ({ questionId }) => questionId === currentQuestion.content.id
  )?.answer as string;
    const theme = useTheme();
  const uploadFile = ({ target }: ChangeEvent<HTMLInputElement>) => {
    const file = target.files?.[0];

    if (file) {
      updateAnswer(
        currentQuestion.content.id,
        `${file.name}|${URL.createObjectURL(file)}`
      );
    }
  };

  return (
    <Box>
      <Typography variant="h5">{currentQuestion.title}</Typography>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
          marginTop: "20px",
          maxWidth: answer?.split("|")[0] ? "640px" : "550px"
        }}
      >
        <ButtonBase component="label" sx={{ justifyContent: "flex-start" }}>
          <input
            onChange={uploadFile}
            hidden
            accept={UPLOAD_FILE_TYPES_MAP[currentQuestion.content.type]}
            multiple
            type="file"
          />
          <UploadBox icon={<UploadIcon />} text="5 MB максимум" />
        </ButtonBase>
        {answer && currentQuestion.content.type === "picture" && (
          <img
            src={answer.split("|")[1]}
            alt=""
            style={{
              marginTop: "15px",
              maxWidth: "300px",
              maxHeight: "300px",
            }}
          />
        )}
        {answer && currentQuestion.content.type === "video" && (
          <video
            src={answer.split("|")[1]}
            style={{
              marginTop: "15px",
              maxWidth: "300px",
              maxHeight: "300px",
              objectFit: "cover",
            }}
          />
        )}
        {answer?.split("|")[0] && (
          <Typography sx={{ marginTop: "15px" }}>
            {answer?.split("|")[0]}
          </Typography>
        )}
      </Box>
    </Box>
  );
};
