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";
import moment from "moment";

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) ?? {};

  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)}
        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
            .filter((v) => {
              if (!v.isOwn) return true;
              return v.isOwn && currentQuestion.content.own;
            })
            .map((variant, index) => (
              <EmojiVariant
                key={variant.id}
                questionId={currentQuestion.id}
                variant={variant}
                index={index}
                isMulti={Boolean(currentQuestion.content.multi)}
                own={Boolean(variant.isOwn)}
                questionLargeCheck={true}
                answer={answer}
                ownPlaceholder={currentQuestion.content?.ownPlaceholder || ""}
              />
            ))}
        </Box>
      </RadioGroup>
    </Box>
  );
};
