import { useState } from "react";
import { useParams } from "react-router-dom";
import { Box, Typography, ButtonBase } from "@mui/material";

import UploadBox from "@ui_kit/UploadBox";

import { questionStore, updateQuestionsList } from "@root/questions";
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 = {
  question: QuizQuestionFile;
};

export const File = ({ question }: FileProps) => {
  const [fileName, setFileName] = useState<string>("");
  const [file, setFile] = useState<string>();
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const totalIndex = listQuestions[quizId].findIndex(
    ({ id }) => question.id === id
  );

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

    if (file) {
      setFileName(file.name);
      setFile(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>
        {fileName && (
          <Typography sx={{ marginTop: "15px" }}>{fileName}</Typography>
        )}
      </Box>
    </Box>
  );
};
