import { useState } from "react";
import { Box, Modal, Typography, useTheme } from "@mui/material";

import { UploadFile } from "./UploadFile";
import { UploadedFile } from "./UploadedFile";

import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import { useQuizViewStore } from "@stores/quizView";

import { ACCEPT_SEND_FILE_TYPES_MAP } from "@/components/ViewPublicationPage/tools/fileUpload";

import type { QuizQuestionFile } from "@model/questionTypes/file";
import { useTranslation } from "react-i18next";
import { sendFile } from "@api/quizRelase";
import { enqueueSnackbar } from "notistack";

export type ModalWarningType = "errorType" | "errorSize" | "picture" | "video" | "audio" | "document" | null;

type FileProps = {
  currentQuestion: QuizQuestionFile;
};

export const File = ({ currentQuestion }: FileProps) => {
  const theme = useTheme();
  const { t } = useTranslation();
  const answers = useQuizViewStore((state) => state.answers);
  const updateAnswer = useQuizViewStore((state) => state.updateAnswer);
  const setFileUploading = useQuizViewStore((state) => state.setFileUploading);
  const [modalWarningType, setModalWarningType] = useState<ModalWarningType>(null);
  const [isSending, setIsSending] = useState<boolean>(false);
  const [isUploading, setIsUploading] = useState<boolean>(false);
  const isMobile = useRootContainerSize() < 500;

  const answer = answers.find(({ questionId }) => questionId === currentQuestion.id)?.answer as string;

  const handleFileUpload = async (file: File) => {
    if (!file) return;

    try {
      setIsUploading(true);
      setFileUploading(currentQuestion.id, true);
      const result = await sendFile({
        questionId: currentQuestion.id,
        body: {
          name: file.name,
          file,
          preview: false,
        },
        qid: window.location.pathname.split("/").pop() || "",
      });

      if (result) {
        updateAnswer(currentQuestion.id, result.fileName, 0);
        enqueueSnackbar(t("File uploaded successfully"));
      }
    } catch (error) {
      console.error(error);
      enqueueSnackbar(t("Failed to upload file"));
    } finally {
      setIsUploading(false);
      setFileUploading(currentQuestion.id, false);
    }
  };

  return (
    <Box>
      <Typography
        variant="h5"
        color={theme.palette.text.primary}
        sx={{ wordBreak: "break-word" }}
      >
        {currentQuestion.title}
      </Typography>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
          marginTop: "20px",
          maxWidth: answer?.split("|")[0] ? "640px" : "600px",
        }}
      >
        {answer?.split("|")[0] ? (
          <UploadedFile
            currentQuestion={currentQuestion}
            setIsSending={setIsSending}
          />
        ) : (
          <UploadFile
            currentQuestion={currentQuestion}
            setModalWarningType={setModalWarningType}
            isSending={isSending}
            setIsSending={setIsSending}
            onFileUpload={handleFileUpload}
            isUploading={isUploading}
          />
        )}
        {answer && currentQuestion.content.type === "picture" && (
          <img
            src={answer.split("|")[1]}
            style={{ marginTop: "15px", maxWidth: "300px", maxHeight: "300px" }}
            alt=""
          />
        )}
        {answer && currentQuestion.content.type === "video" && (
          <video
            src={answer.split("|")[1]}
            style={{
              marginTop: "15px",
              maxWidth: "300px",
              maxHeight: "300px",
              objectFit: "cover",
            }}
          />
        )}
      </Box>
      <Modal
        open={modalWarningType !== null}
        onClose={() => setModalWarningType(null)}
      >
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: isMobile ? 300 : 400,
            bgcolor: "background.paper",
            borderRadius: 3,
            boxShadow: 24,
            p: 4,
          }}
        >
          <CurrentModal status={modalWarningType} />
        </Box>
      </Modal>
    </Box>
  );
};

const CurrentModal = ({ status }: { status: ModalWarningType }) => {
  const { t } = useTranslation();
  switch (status) {
    case null:
      return null;
    case "errorType":
      return <Typography>{t("Incorrect file type selected")}</Typography>;
    case "errorSize":
      return <Typography>{t("File is too big. Maximum size is 50 MB")}</Typography>;

    default:
      return (
        <>
          <Typography>{t("Acceptable file extensions")}:</Typography>
          <Typography>{ACCEPT_SEND_FILE_TYPES_MAP[status].join(" ")}</Typography>
        </>
      );
  }
};
