import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import type { QuizQuestionImages } from "@model/questionTypes/images";
import { Box, RadioGroup, Typography, useTheme } from "@mui/material";
import { createQuizViewStore, useQuizViewStore } from "@stores/quizView";
import { ImageVariant } from "./ImageVariant";
import moment from "moment";

type ImagesProps = {
  currentQuestion: QuizQuestionImages;
};

export const Images = ({ currentQuestion }: ImagesProps) => {
  const answers = useQuizViewStore((state) => state.answers);
  const theme = useTheme();
  const answer = answers.find(({ questionId }) => questionId === currentQuestion.id)?.answer;
  const isTablet = useRootContainerSize() < 1000;
  const isMobile = useRootContainerSize() < 500;

  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>
      <RadioGroup
        name={currentQuestion.id}
        value={currentQuestion.content.variants.findIndex(({ id }) => answer === id)}
        sx={{
          display: "flex",
          flexWrap: "wrap",
          flexDirection: "row",
          justifyContent: "space-between",
          marginTop: "20px",
        }}
      >
        <Box
          sx={{
            display: "grid",
            gap: "15px",
            gridTemplateColumns: isTablet ? (isMobile ? "repeat(1, 1fr)" : "repeat(2, 1fr)") : "repeat(3, 1fr)",
            width: "100%",
          }}
        >
          {currentQuestion.content.variants
            .filter((v) => {
              if (!v.isOwn) return true;
              return v.isOwn && currentQuestion.content.own;
            })
            .map((variant, index) => (
              <ImageVariant
                key={variant.id}
                questionId={currentQuestion.id}
                variant={variant}
                index={index}
                answer={answer}
                isMulti={Boolean(currentQuestion.content.multi)}
                own={Boolean(variant.isOwn)}
                questionLargeCheck={true}
                ownPlaceholder={currentQuestion.content?.ownPlaceholder || ""}
              />
            ))}
        </Box>
      </RadioGroup>
    </Box>
  );
};
