import { useState } from "react";
import { useParams } from "react-router-dom";
import {
  Box,
  Typography,
  RadioGroup,
  FormControlLabel,
  Radio,
  useTheme,
} from "@mui/material";

import { questionStore } from "@root/questions";

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

import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";

type VarimgProps = {
  question: QuizQuestionVarImg;
};

export const Varimg = ({ question }: VarimgProps) => {
  const [valueIndex, setValueIndex] = useState<number>(-1);
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();
  const totalIndex = listQuestions[quizId].findIndex(
    ({ id }) => question.id === id
  );

  return (
    <Box>
      <Typography variant="h5">{question.title}</Typography>
      <Box sx={{ display: "flex" }}>
        <RadioGroup
          name={question.id}
          value={valueIndex}
          onChange={({ target }) => setValueIndex(Number(target.value))}
          sx={{
            display: "flex",
            flexWrap: "wrap",
            flexDirection: "row",
            justifyContent: "space-between",
            flexBasis: "100%",
            marginTop: "20px",
          }}
        >
          <Box sx={{ display: "flex", flexDirection: "column", width: "100%" }}>
            {question.content.variants.map(({ id, answer }, 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",
                }}
                value={index}
                control={
                  <Radio checkedIcon={<RadioCheck />} icon={<RadioIcon />} />
                }
                label={answer}
              />
            ))}
          </Box>
        </RadioGroup>
        {(question.content.variants[valueIndex]?.extendedText ||
          question.content.back) && (
          <Box sx={{ maxWidth: "400px", width: "100%", height: "300px" }}>
            <img
              src={
                valueIndex >= 0
                  ? question.content.variants[valueIndex].extendedText
                  : question.content.back
              }
              style={{ width: "100%", height: "100%", objectFit: "cover" }}
              alt=""
            />
          </Box>
        )}
      </Box>
    </Box>
  );
};
