import type { QuizQuestionEmoji } from "@model/questionTypes/emoji";
import { Box, RadioGroup, Typography, useTheme } from "@mui/material";
import { useQuizViewStore } from "@stores/quizView";
import { polyfillCountryFlagEmojis } from "country-flag-emoji-polyfill";
import { EmojiVariant } from "./EmojiVariant";

polyfillCountryFlagEmojis();

type EmojiProps = {
  currentQuestion: QuizQuestionEmoji;
};

export const Emoji = ({ currentQuestion }: EmojiProps) => {
  const answers = useQuizViewStore((state) => state.answers);
  const { updateAnswer } = useQuizViewStore((state) => state);
  const theme = useTheme();
  const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};

  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)}
        onChange={({ target }) =>
          updateAnswer(
            currentQuestion.id,
            currentQuestion.content.variants[Number(target.value)].answer,
            currentQuestion.content.variants[Number(target.value)].points || 0
          )
        }
        sx={{
          display: "flex",
          flexWrap: "wrap",
          flexDirection: "row",
          justifyContent: "space-between",
          marginTop: "20px",
        }}
      >
        <Box sx={{ display: "flex", width: "100%", gap: "42px", flexWrap: "wrap" }}>
          {currentQuestion.content.variants.map((variant, index) => (
            <EmojiVariant
              key={variant.id}
              questionId={currentQuestion.id}
              variant={variant}
              index={index}
            />
          ))}
        </Box>
      </RadioGroup>
    </Box>
  );
};
