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

import { useQuizViewStore, updateAnswer } from "@root/quizView";

import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";

import type { QuizQuestionEmoji } from "../../../model/questionTypes/emoji";

type EmojiProps = {
  stepNumber: number;
  question: QuizQuestionEmoji;
};

export const Emoji = ({ stepNumber, question }: EmojiProps) => {
  const { answers } = useQuizViewStore();
  const theme = useTheme();
  const { answer } = answers.find(({ step }) => step === stepNumber) ?? {};

  useEffect(() => {
    if (!answer) {
      updateAnswer(stepNumber, question.content.variants[0].id);
    }
  }, []);

  return (
    <Box>
      <Typography variant="h5">{question.title}</Typography>
      <RadioGroup
        name={question.id}
        value={question.content.variants.findIndex(({ id }) => answer === id)}
        onChange={({ target }) =>
          updateAnswer(
            stepNumber,
            question.content.variants[Number(target.value)].id
          )
        }
        sx={{
          display: "flex",
          flexWrap: "wrap",
          flexDirection: "row",
          justifyContent: "space-between",
          marginTop: "20px",
        }}
      >
        <Box sx={{ display: "flex", flexDirection: "column", width: "100%" }}>
          {question.content.variants.map(
            ({ id, answer, extendedText }, index) => (
              <FormControlLabel
                key={id}
                sx={{
                  marginBottom: "15px",
                  borderRadius: "5px",
                  padding: "15px",
                  color: theme.palette.grey2.main,
                  border: `1px solid ${theme.palette.grey2.main}`,
                  display: "flex",
                  gap: "10px",
                }}
                value={index}
                control={
                  <Radio checkedIcon={<RadioCheck />} icon={<RadioIcon />} />
                }
                label={
                  <Box sx={{ display: "flex", gap: "10px" }}>
                    <Typography>{extendedText}</Typography>
                    <Typography>{answer}</Typography>
                  </Box>
                }
              />
            )
          )}
        </Box>
      </RadioGroup>
    </Box>
  );
};
