import React, { forwardRef, useState } from "react";
import { useQuizViewStore } from "@stores/quizView";
import { useQuizStore } from "@/stores/useQuizStore";
import { useSnackbar } from "notistack";
import { useTranslation } from "react-i18next";
import { sendFile } from "@/api/quizRelase";
import { ACCEPT_SEND_FILE_TYPES_MAP, MAX_FILE_SIZE } from "../../tools/fileUpload";

interface OwnVarimgImageProps {
  questionId: string;
  variantId: string;
}

export const OwnVarimgImage = forwardRef<HTMLInputElement, OwnVarimgImageProps>(({ questionId, variantId }, ref) => {
  const { updateAnswer, updateOwnVariant } = useQuizViewStore((state) => state);
  const { quizId, preview } = useQuizStore();
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useTranslation();

  const [isUploading, setIsUploading] = useState(false);

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

    // Валидация размера файла
    if (file.size > MAX_FILE_SIZE) {
      enqueueSnackbar(t("file is too big"), { variant: "warning" });
      return;
    }

    // Валидация типа файла
    const isFileTypeAccepted = ACCEPT_SEND_FILE_TYPES_MAP.picture.some((fileType) =>
      file.name.toLowerCase().endsWith(fileType)
    );
    if (!isFileTypeAccepted) {
      enqueueSnackbar(t("file type is not supported"), { variant: "warning" });
      return;
    }

    setIsUploading(true);
    try {
      const data = await sendFile({
        questionId,
        body: { file, name: file.name, preview },
        qid: quizId,
      });

      const fileId = data?.data.fileIDMap[questionId];
      const localImageUrl = URL.createObjectURL(file);

      updateOwnVariant(variantId, null, "", fileId, localImageUrl);
      // Убираем автоматический выбор own варианта - загрузка возможна только при выбранном own варианте
      // updateAnswer(questionId, variantId, 0);
    } catch (error) {
      console.error("Error uploading image:", error);
      enqueueSnackbar(t("The answer was not counted"));
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      uploadImage(file);
      event.target.value = "";
    }
  };

  return (
    <input
      type="file"
      ref={ref}
      style={{ display: "none" }}
      accept={ACCEPT_SEND_FILE_TYPES_MAP.picture.join(",")}
      onChange={handleFileChange}
      disabled={isUploading}
    />
  );
});

OwnVarimgImage.displayName = "OwnVarimgImage";
