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

import { deleteAnswer, updateAnswer, useQuizViewStore } from "@stores/quizView/store";
import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";

import { sendAnswer } from "@api/quizRelase";
import { enqueueSnackbar } from "notistack";
import { useQuizId } from "../../../contexts/QuizIdContext";
import { useRootContainerSize } from "../../../contexts/RootContainerWidthContext";
import type { QuizQuestionImages } from "../../../model/questionTypes/images";

type ImagesProps = {
    currentQuestion: QuizQuestionImages;
};

export const Images = ({ currentQuestion }: ImagesProps) => {
    const qid = useQuizId();
    const { answers } = useQuizViewStore();
    const theme = useTheme();
    const answer = answers.find(({ questionId }) => questionId === currentQuestion.id)?.answer;
    const isTablet = useRootContainerSize() < 1000;
    const isMobile = useRootContainerSize() < 500;

    return (
        <Box>
            <Typography variant="h5" color={theme.palette.text.primary}>{currentQuestion.title}</Typography>
            <RadioGroup
                name={currentQuestion.id}
                value={currentQuestion.content.variants.findIndex(
                    ({ id }) => answer === id
                )}
                sx={{
                    display: "flex",
                    flexWrap: "wrap",
                    flexDirection: "row",
                    justifyContent: "space-between",
                    marginTop: "20px",
                }}
            >
                <Box
                    sx={{
                        display: "grid",
                        gap: "15px",
                        gridTemplateColumns: isTablet
                            ? isMobile
                                ? "repeat(1, 1fr)"
                                : "repeat(2, 1fr)"
                            : "repeat(3, 1fr)",
                        width: "100%",
                    }}
                >
                    {currentQuestion.content.variants.map((variant, index) => (
                        <Box
                            key={index}
                            sx={{
                                cursor: "pointer",
                                borderRadius: "5px",
                                border: `1px solid`,
                                borderColor: answer === variant.id ? theme.palette.primary.main : "#9A9AAF",
                            }}
                            onClick={async (event) => {
                                event.preventDefault();

                                try {

                                    await sendAnswer({
                                        questionId: currentQuestion.id,
                                        body: `${currentQuestion.content.variants[index].answer} <img style="width:100%; max-width:250px; max-height:250px" src="${currentQuestion.content.variants[index].extendedText}"/>`,
                                        qid,
                                    });

                                    updateAnswer(
                                        currentQuestion.id,
                                        currentQuestion.content.variants[index].id,
                                        currentQuestion.content.variants[index].points || 0
                                    );

                                } catch (e) {
                                    enqueueSnackbar("ответ не был засчитан");
                                }


                                if (answer === currentQuestion.content.variants[index].id) {
                                    deleteAnswer(currentQuestion.id);
                                    try {

                                        await sendAnswer({
                                            questionId: currentQuestion.id,
                                            body: "",
                                            qid,
                                        });

                                    } catch (e) {
                                        enqueueSnackbar("ответ не был засчитан");
                                    }
                                }
                            }}
                        >
                            <Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
                                <Box sx={{ width: "100%", height: "300px" }}>
                                    {variant.extendedText && (
                                        <img
                                            src={variant.extendedText}
                                            alt=""
                                            style={{
                                                display: "block",
                                                width: "100%",
                                                height: "100%",
                                                objectFit: "cover",
                                            }}
                                        />
                                    )}
                                </Box>
                            </Box>
                            <FormControlLabel
                                key={variant.id}
                                sx={{
                                    textAlign: "center",
                                    color: theme.palette.text.primary,
                                    marginTop: "10px",
                                    marginLeft: 0,
                                    padding: "10px",
                                    "& .MuiFormControlLabel-label": {
                                        wordBreak: "break-word",
                                    },
                                }}
                                value={index}
                                control={
                                    <Radio checkedIcon={<RadioCheck color={theme.palette.primary.main} />} icon={<RadioIcon />} />
                                }
                                label={variant.answer}
                            />
                        </Box>
                    ))}
                </Box>
            </RadioGroup>
        </Box>
    );

};
