import { Box, Typography, ButtonBase } from "@mui/material";

import UploadBox from "@ui_kit/UploadBox";

import { useQuizViewStore, updateAnswer } from "@root/quizView";
import { UPLOAD_FILE_TYPES_MAP } from "@ui_kit/QuizPreview/QuizPreviewQuestionTypes/File";

import UploadIcon from "@icons/UploadIcon";

import type { ChangeEvent } from "react";
import type { QuizQuestionFile } from "../../../model/questionTypes/file";

type FileProps = {
  stepNumber: number;
  question: QuizQuestionFile;
};

export const File = ({ stepNumber, question }: FileProps) => {
  const { answers } = useQuizViewStore();
  const { answer } = answers.find(({ step }) => step === stepNumber) ?? {};

  const uploadFile = ({ target }: ChangeEvent<HTMLInputElement>) => {
    const file = target.files?.[0];

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

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