import {
    Box,
    Checkbox,
    FormControlLabel,
    FormGroup,
    Radio,
    RadioGroup,
    TextField as MuiTextField,
    Typography,
    useTheme,
    TextFieldProps, useMediaQuery,
} from "@mui/material";
import { FC, useEffect } from "react";

import {
    deleteAnswer,
    updateAnswer,
    updateOwnVariant,
    useQuizViewStore
} from "@stores/quizView/store";

import { CheckboxIcon } from "@icons/Checkbox";
import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";

import { sendAnswer } from "@api/quizRelase";

import { quizThemes } from "@utils/themes/Publication/themePublication";
import { enqueueSnackbar } from "notistack";
import type { QuestionVariant } from "../../../model/questionTypes/shared";
import type { QuizQuestionVariant } from "../../../model/questionTypes/variant";
import { useQuizData } from "@utils/hooks/useQuizData";
import { useQuizId } from "../../../contexts/QuizIdContext";

const TextField = MuiTextField as unknown as FC<TextFieldProps>;

type VariantProps = {
    currentQuestion: QuizQuestionVariant;
};

type VariantItemProps = {
    currentQuestion: QuizQuestionVariant;
    variant: QuestionVariant;
    answer: string | string[] | undefined;
    index: number;
    own?: boolean;
};

export const Variant = ({ currentQuestion }: VariantProps) => {
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down(650));
    const { answers, ownVariants } = useQuizViewStore();
    const { answer } =
        answers.find(
            ({ questionId }) => questionId === currentQuestion.id
        ) ?? {};
    const ownVariant = ownVariants.find(
        (variant) => variant.id === currentQuestion.id
    );

    const Group = currentQuestion.content.multi ? FormGroup : RadioGroup;

    useEffect(() => {
        if (!ownVariant) {
            updateOwnVariant(currentQuestion.id, "");
        }
    }, []);

    return (
        <Box>
            <Typography variant="h5" color={theme.palette.text.primary}>{currentQuestion.title}</Typography>
            <Box sx={{ display: "flex", gap: "20px",
                flexDirection: isMobile ? "column-reverse" : undefined, }}>
                <Group
                    name={currentQuestion.id.toString()}
                    value={currentQuestion.content.variants.findIndex(
                        ({ id }) => answer === 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((variant, index) => (
                            <VariantItem
                                key={variant.id}
                                currentQuestion={currentQuestion}
                                variant={variant}
                                // @ts-ignore
                                answer={answer}
                                index={index}
                            />
                        ))}
                        {currentQuestion.content.own && ownVariant && (
                            <VariantItem
                                own
                                currentQuestion={currentQuestion}
                                variant={ownVariant.variant}
                                // @ts-ignore
                                answer={answer}
                                index={currentQuestion.content.variants.length + 2}
                            />
                        )}
                    </Box>
                </Group>
                {currentQuestion.content.back && currentQuestion.content.back !== " " && (
                    <Box sx={{ maxWidth: "400px", width: "100%", height: "300px" }}>
                        <img
                            key={currentQuestion.id}
                            src={currentQuestion.content.back}
                            style={{ width: "100%", height: "100%", objectFit: "cover" }}
                            alt=""
                        />
                    </Box>
                )}
            </Box>
        </Box>
    );
};

const VariantItem = ({
    currentQuestion,
    variant,
    answer,
    index,
    own = false,
}: VariantItemProps) => {
    const theme = useTheme();
    const { settings } = useQuizData();
    const qid = useQuizId();

    return (
        <FormControlLabel
            key={variant.id}
            sx={{
                margin: "0",
                borderRadius: "12px",
                color: theme.palette.text.primary,
                padding: "15px",
                border: `1px solid`,
                borderColor: answer === variant.id
                    ? theme.palette.primary.main
                    : "#9A9AAF",
                backgroundColor: quizThemes[settings.cfg.theme].isLight
                    ? "white"
                    : theme.palette.background.default,
                display: "flex",
                maxWidth: "685px",
                maxHeight: "85px",
                justifyContent: "space-between",
                width: "100%",
                "&.MuiFormControl-root": {
                    width: "100%",
                },
                "& .MuiFormControlLabel-label": {
                    wordBreak: "break-word"
                }
            }}
            value={index}
            labelPlacement="start"
            control={
                currentQuestion.content.multi ?
                    <Checkbox
                        checked={!!answer?.includes(variant.id)}
                        checkedIcon={<CheckboxIcon checked color={theme.palette.primary.main} />}
                        icon={<CheckboxIcon />}
                    />
                    :
                    <Radio checkedIcon={<RadioCheck color={theme.palette.primary.main} />} icon={<RadioIcon />} />
            }
            label={own ? <TextField label="Другое..." /> : variant.answer}
            onClick={async (event) => {
                event.preventDefault();
                const variantId = currentQuestion.content.variants[index].id;
                console.log(answer)

                if (currentQuestion.content.multi) {
                    const currentAnswer = typeof answer !== "string" ? answer || [] : [];

                    try {
                        await sendAnswer({
                            questionId: currentQuestion.id,
                            body: currentAnswer.includes(variantId)
                                ? currentAnswer?.filter((item) => item !== variantId)
                                : [...currentAnswer, variantId],
                            qid,
                        });

                        updateAnswer(
                            currentQuestion.id,
                            currentAnswer.includes(variantId)
                                ? currentAnswer?.filter((item) => item !== variantId)
                                : [...currentAnswer, variantId],
                            currentQuestion.content.variants[index].points || 0
                        );
                    } catch (e) {
                        console.log(e)
                        enqueueSnackbar("ответ не был засчитан");
                    }

                    return;
                }

                try {
                    await sendAnswer({
                        questionId: currentQuestion.id,
                        body: currentQuestion.content.variants[index].answer,
                        qid,
                    });

                    updateAnswer(currentQuestion.id, variantId,
                        answer === variantId ? 0
                            :
                            currentQuestion.content.variants[index].points || 0
                    );

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

                if (answer === variantId) {
                    try {

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

                    } catch (e) {
                        console.log(e)
                        enqueueSnackbar("ответ не был засчитан");
                    }
                    deleteAnswer(currentQuestion.id);
                }
            }}
        />
    );
};
