import {
    Box,
    Typography,
    RadioGroup,
    FormControlLabel,
    Radio,
    useTheme,
    useMediaQuery
} from "@mui/material";
import { useQuizViewStore, updateAnswer, deleteAnswer } from "@stores/quizView/store";

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

import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";
import { enqueueSnackbar } from "notistack";
import { sendAnswer } from "@api/quizRelase";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import BlankImage from "@icons/BlankImage";
import { useQuizData } from "@utils/hooks/useQuizData";

type VarimgProps = {
    currentQuestion: QuizQuestionVarImg;
};

export const Varimg = ({ currentQuestion }: VarimgProps) => {
    const { settings } = useQuizData();
    const { answers } = useQuizViewStore();
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down(650));

    const { answer } =
        answers.find(
            ({ questionId }) => questionId === currentQuestion.id
        ) ?? {};
    const variant = currentQuestion.content.variants.find(
        ({ id }) => answer === id
    );

    return (
        <Box>
            <Typography variant="h5" color={theme.palette.text.primary}>{currentQuestion.title}</Typography>
            <Box sx={{
                display: "flex",
                marginTop: "20px",
                flexDirection: isMobile ? "column-reverse" : undefined,
                gap: isMobile ? "30px" : undefined

            }}>
                <RadioGroup
                    name={currentQuestion.id}
                    value={currentQuestion.content.variants.findIndex(
                        ({ id }) => answer === id
                    )}
                    sx={{
                        display: "flex",
                        flexWrap: "wrap",
                        flexDirection: "row",
                        justifyContent: "space-between",
                        flexBasis: "100%",
                    }}
                >
                    <Box sx={{ display: "flex", flexDirection: "column", width: "100%", gap: isMobile ? "20px" : undefined }}>
                        {currentQuestion.content.variants.map((variant, index) => (
                            <FormControlLabel
                                key={variant.id}
                                sx={{
                                    marginBottom: "15px",
                                    borderRadius: "5px",
                                    padding: "15px",
                                    color: theme.palette.text.primary,
                                    backgroundColor: quizThemes[settings.cfg.theme].isLight ? "white" : theme.palette.background.default,
                                    border: `1px solid`,
                                    borderColor: answer === variant.id ? theme.palette.primary.main : "#9A9AAF",
                                    display: "flex",
                                    margin: isMobile ? 0 : undefined,
                                    "& .MuiFormControlLabel-label": {
                                        wordBreak: "break-word"
                                    }
                                }}
                                value={index}
                                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: settings.qid
                                        });

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

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


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

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

                                        } catch (e) {
                                            enqueueSnackbar("ответ не был засчитан");
                                        }
                                        deleteAnswer(currentQuestion.id);
                                    }
                                }}
                                control={
                                    <Radio checkedIcon={<RadioCheck color={theme.palette.primary.main} />} icon={<RadioIcon />} />
                                }
                                label={variant.answer}
                            />
                        ))}
                    </Box>
                </RadioGroup>
                {/* {(variant?.extendedText || currentQuestion.content.back) && ( */}
                <Box
                    sx={{
                        maxWidth: "450px",
                        width: "100%",
                        height: "450px",
                        border: "1px solid #9A9AAF",
                        borderRadius: "12px",
                        overflow: "hidden",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        backgroundColor: "#9A9AAF12",
                        color: "#9A9AAF"
                    }}
                >
                    {answer ? (
                        variant?.extendedText ? (
                            <img
                                src={variant?.extendedText}
                                style={{ width: "100%", height: "100%", objectFit: "cover" }}
                                alt=""
                            />
                        ) : (
                            <BlankImage />
                        )
                    ) : (currentQuestion.content.replText !== " " && currentQuestion.content.replText.length > 0) ? currentQuestion.content.replText : variant?.extendedText || isMobile ? (
                        "Выберите вариант ответа ниже"
                    ) : (
                        "Выберите вариант ответа слева"
                    )}

                </Box>
                {/* )} */}
            </Box>
        </Box>
    );

};
