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

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

import CloseBold from "@icons/CloseBold";

import type { QuizQuestionFile } from "@model/questionTypes/file";

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

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

  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}>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>
  );
};
