import { useEffect, useMemo, useRef, useState } from "react";
import { Box, ButtonBase, RadioGroup, Typography, useTheme, IconButton } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

import { VarimgVariant } from "./VarimgVariant";
import { OwnVarimgImage } from "./OwnVarimgImage";

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

import BlankImage from "@icons/BlankImage";

import type { QuizQuestionVarImg } from "@model/questionTypes/varimg";
import moment from "moment";
import { useTranslation } from "react-i18next";

type VarimgProps = {
  currentQuestion: QuizQuestionVarImg;
};

export const Varimg = ({ currentQuestion }: VarimgProps) => {
  const [isSending, setIsSending] = useState<boolean>(false);
  const answers = useQuizViewStore((state) => state.answers);
  const ownVariants = useQuizViewStore((state) => state.ownVariants);
  const updateOwnVariant = useQuizViewStore((state) => state.updateOwnVariant);
  const { t } = useTranslation();

  const theme = useTheme();
  const isMobile = useRootContainerSize() < 650;
  const isTablet = useRootContainerSize() < 850;

  const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};
  const ownVariant = ownVariants.find((variant) => variant.id === currentQuestion.id);
  const variant = currentQuestion.content.variants.find(({ id }) => answer === id);
  const ownVariantInQuestion = useMemo(
    () => currentQuestion.content.variants.find((v) => v.isOwn),
    [currentQuestion.content.variants]
  );
  const ownVariantData = ownVariants.find((v) => v.id === answer);
  const ownImageUrl = useMemo(() => {
    return ownVariantData?.variant.localImageUrl;
  }, [ownVariantData]);

  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!ownVariant) {
      updateOwnVariant(currentQuestion.id, "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const choiceImgUrlAnswer = useMemo(() => {
    if (variant !== undefined) {
      if (variant.editedUrlImagesList !== undefined && variant.editedUrlImagesList !== null) {
        return variant.editedUrlImagesList[isMobile ? "mobile" : isTablet ? "tablet" : "desktop"];
      } else {
        return variant.extendedText;
      }
    }
  }, [variant]);

  const choiceImgUrlQuestion = useMemo(() => {
    if (
      currentQuestion.content.editedUrlImagesList !== undefined &&
      currentQuestion.content.editedUrlImagesList !== null
    ) {
      return currentQuestion.content.editedUrlImagesList[isMobile ? "mobile" : isTablet ? "tablet" : "desktop"];
    } else {
      return currentQuestion.content.back;
    }
  }, [variant]);

  const handlePreviewAreaClick = () => {
    // Загрузка возможна только если own вариант выбран
    if (ownVariantInQuestion && answer === ownVariantInQuestion.id) {
      inputRef.current?.click();
    }
  };

  const handleRemoveImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (ownVariantData) {
      // Сохраняем текущий answer, очищаем только изображения
      const currentAnswer = ownVariantData.variant.answer || "";
      updateOwnVariant(ownVariantData.id, currentAnswer, "", "", "");
    }
  };

  if (moment.isMoment(answer)) throw new Error("Answer is Moment in Variant question");

  return (
    <Box>
      <Typography
        variant="h5"
        color={theme.palette.text.primary}
        sx={{ wordBreak: "break-word" }}
      >
        {currentQuestion.title}
      </Typography>
      <Box
        sx={{
          display: "flex",
          marginTop: "20px",
          flexDirection: isMobile ? "column-reverse" : undefined,
          gap: "30px",
          alignItems: isMobile ? "center" : undefined,
        }}
      >
        <RadioGroup
          name={currentQuestion.id}
          value={currentQuestion.content.variants.findIndex(({ id }) => answer === id)}
          sx={{
            display: "flex",
            flexWrap: "wrap",
            flexDirection: "row",
            justifyContent: "space-between",
            flexBasis: "100%",
            width: isMobile ? "100%" : undefined,
          }}
        >
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              width: "100%",
              gap: "20px",
              "&:focus": { color: theme.palette.text.primary },
              "&:active": { color: theme.palette.text.primary },
            }}
          >
            {currentQuestion.content.variants
              .filter((v) => {
                if (!v.isOwn) return true;
                return v.isOwn && currentQuestion.content.own;
              })
              .map((variant, index) => (
                <VarimgVariant
                  key={variant.id}
                  questionId={currentQuestion.id}
                  variant={variant}
                  isSending={isSending}
                  setIsSending={setIsSending}
                  index={index}
                  questionLargeCheck={currentQuestion.content.largeCheck}
                  ownPlaceholder={currentQuestion.content?.ownPlaceholder || ""}
                  isMulti={Boolean(currentQuestion.content?.multi)}
                  answer={answer}
                />
              ))}
            {ownVariantInQuestion && (
              <OwnVarimgImage
                ref={inputRef}
                questionId={currentQuestion.id}
                variantId={ownVariantInQuestion.id}
              />
            )}
          </Box>
        </RadioGroup>
        <ButtonBase
          onClick={handlePreviewAreaClick}
          disabled={!ownVariantInQuestion || answer !== ownVariantInQuestion.id}
          sx={{
            maxWidth: "450px",
            width: "100%",
            height: "450px",
            border: "1px solid #9A9AAF",
            borderRadius: "12px",
            overflow: "hidden",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            backgroundColor: "#9A9AAF30",
            color: theme.palette.text.primary,
            textAlign: "center",
            position: "relative",
            "&:hover": {
              backgroundColor:
                ownVariantInQuestion && answer === ownVariantInQuestion.id ? "rgba(0,0,0,0.04)" : "transparent",
            },
          }}
        >
          {(() => {
            if (answer) {
              const imageUrl = variant?.isOwn && ownImageUrl ? ownImageUrl : choiceImgUrlAnswer;
              if (imageUrl) {
                return (
                  <>
                    <img
                      key={imageUrl}
                      src={imageUrl}
                      style={{ width: "100%", height: "100%", objectFit: "cover" }}
                      alt=""
                    />
                    {variant?.isOwn && ownImageUrl && (
                      <IconButton
                        onClick={handleRemoveImage}
                        sx={{
                          position: "absolute",
                          top: 8,
                          left: 8,
                          zIndex: 1,
                          backgroundColor: "rgba(0, 0, 0, 0.5)",
                          color: "white",
                          height: "25px",
                          width: "25px",
                          "&:hover": {
                            backgroundColor: "rgba(0, 0, 0, 0.7)",
                          },
                        }}
                      >
                        <CloseIcon />
                      </IconButton>
                    )}
                  </>
                );
              }
              return (
                <Box
                  sx={{
                    position: "relative",
                    width: "100%",
                    height: "100%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <BlankImage />
                  {variant?.isOwn && (
                    <Box
                      sx={{
                        position: "absolute",
                        top: "50%",
                        left: "50%",
                        transform: "translate(-50%, -50%)",
                        zIndex: 1,
                      }}
                    >
                      {t("Add your image")}
                    </Box>
                  )}
                </Box>
              );
            }

            if (choiceImgUrlQuestion && choiceImgUrlQuestion.trim().length > 0) {
              return (
                <img
                  src={choiceImgUrlQuestion}
                  style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  alt=""
                />
              );
            }

            if (currentQuestion.content.replText && currentQuestion.content.replText.trim().length > 0) {
              return currentQuestion.content.replText;
            }

            return isMobile ? t("Select an answer option below") : t("Select an answer option on the left");
          })()}
        </ButtonBase>
      </Box>
    </Box>
  );
};
