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 { QuizQuestionVariant } from "../../../model/questionTypes/variant";

type VariantProps = {
  stepNumber: number;
  currentQuestion: QuizQuestionVariant;
};

export const Variant = ({ currentQuestion }: VariantProps) => {
  const { answers } = useQuizViewStore();
  const theme = useTheme();
  const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.content.id) ?? {};

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

  return (
    <Box>
      <Typography variant="h5">{currentQuestion.title}</Typography>
      <Box sx={{ display: "flex" }}>
        <RadioGroup
          name={currentQuestion.id}
          value={currentQuestion.content.variants.findIndex(({ id }) => answer === id)}
          onChange={({ target }) =>
            updateAnswer(
              currentQuestion.content.id,
              currentQuestion.content.variants[Number(target.value)].id
            )
          }
          sx={{
            display: "flex",
            flexWrap: "wrap",
            flexDirection: "row",
            justifyContent: "space-between",
            flexBasis: "100%",
            marginTop: "20px",
          }}
        >
          <Box sx={{ display: "flex", flexDirection: "row", flexWrap: "wrap", width: "100%", gap: "20px", }}>
            {currentQuestion.content.variants.map(({ id, answer }, index) => (
              <FormControlLabel
                key={id}
                sx={{
                  margin: "0",
                  borderRadius: "12px",
                  padding: "15px",
                  border: `1px solid ${theme.palette.grey2.main}`,
                  display: "flex",
                  maxWidth: "685px",
                  justifyContent: "space-between",
                  width: "100%"
                }}
                value={index}
                labelPlacement="start"
                control={
                  <Radio checkedIcon={<RadioCheck />} icon={<RadioIcon />} />
                }
                label={answer}
              />
            ))}
          </Box>
        </RadioGroup>
        {currentQuestion.content.back && (
          <Box sx={{ maxWidth: "400px", width: "100%", height: "300px" }}>
            <img
              src={currentQuestion.content.back}
              style={{ width: "100%", height: "100%", objectFit: "cover" }}
              alt=""
            />
          </Box>
        )}
      </Box>
    </Box>
  );
};
