import { useState } from "react";
import { Box, RadioGroup, Typography, useTheme } from "@mui/material";

import { ImageVariant } from "./ImageVariant";

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

import type { QuizQuestionImages } from "@model/questionTypes/images";

type ImagesProps = {
  currentQuestion: QuizQuestionImages;
};

export const Images = ({ currentQuestion }: ImagesProps) => {
  const [isSending, setIsSending] = useState<boolean>(false);
  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;

  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.map((variant, index) => (
            <ImageVariant
              key={variant.id}
              currentQuestion={currentQuestion}
              variant={variant}
              isSending={isSending}
              setIsSending={setIsSending}
              index={index}
            />
          ))}
        </Box>
      </RadioGroup>
    </Box>
  );
};
