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

import { sendAnswer } from "@api/quizRelase";
import { useQuizViewStore } from "@stores/quizView";

import CloseBold from "@icons/CloseBold";

import type { QuizQuestionFile } from "@model/questionTypes/file";
import { useQuizStore } from "@/stores/useQuizStore";
import { useTranslation } from "react-i18next";

type UploadedFileProps = {
  currentQuestion: QuizQuestionFile;
  setIsSending: (isSending: boolean) => void;
};

export const UploadedFile = ({ currentQuestion, setIsSending }: UploadedFileProps) => {
  const { quizId, preview } = useQuizStore();
  const answers = useQuizViewStore((state) => state.answers);
  const { updateAnswer } = useQuizViewStore((state) => state);
  const theme = useTheme();
  const { t } = useTranslation();

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

  const deleteFile = async () => {
    if (answer.length > 0) {
      setIsSending(true);

      await sendAnswer({
        questionId: currentQuestion.id,
        body: "",
        qid: quizId,
        preview,
      });
    }

    updateAnswer(currentQuestion.id, "", 0);
    setIsSending(false);
  };

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: "15px" }}>
      <Typography color={theme.palette.text.primary}>{t("You have uploaded")}:</Typography>
      <Box
        sx={{
          padding: "5px 5px 5px 16px",
          backgroundColor: theme.palette.primary.main,
          borderRadius: "8px",
          color: "#FFFFFF",
          display: "flex",
          alignItems: "center",
          overflow: "hidden",
          gap: "15px",
        }}
      >
        <Typography
          sx={{
            whiteSpace: "nowrap",
            textOverflow: "ellipsis",
            overflow: "hidden",
          }}
        >
          {answer?.split("|")[0]}
        </Typography>
        <IconButton
          sx={{ p: 0 }}
          onClick={deleteFile}
        >
          <CloseBold />
        </IconButton>
      </Box>
    </Box>
  );
};
