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

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

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

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

import { enqueueSnackbar } from "notistack";
import type { QuizQuestionEmoji } from "../../../model/questionTypes/emoji";
import { useQuizData } from "@contexts/QuizDataContext";
import { polyfillCountryFlagEmojis } from "country-flag-emoji-polyfill";
import { quizThemes } from "@utils/themes/Publication/themePublication";

polyfillCountryFlagEmojis();
import { useState } from "react";

type EmojiProps = {
  currentQuestion: QuizQuestionEmoji;
};

export const Emoji = ({ currentQuestion }: EmojiProps) => {
  const theme = useTheme();
  const { quizId, settings } = useQuizData();
  const { answers } = useQuizViewStore();
  const { answer } =
    answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};
  const [isSending, setIsSending] = useState<boolean>(false);

  return (
    <Box>
      <Typography
        variant="h5"
        color={theme.palette.text.primary}
        sx={{ wordBreak: "break-word" }}
      >
        {currentQuestion.title}
      </Typography>
      <RadioGroup
        name={currentQuestion.id}
        value={currentQuestion.content.variants.findIndex(
          ({ id }) => answer === id
        )}
        onChange={({ target }) => {
          updateAnswer(
            currentQuestion.id,
            currentQuestion.content.variants[Number(target.value)].answer,
            currentQuestion.content.variants[Number(target.value)].points || 0
          );
        }}
        sx={{
          display: "flex",
          flexWrap: "wrap",
          flexDirection: "row",
          justifyContent: "space-between",
          marginTop: "20px",
        }}
      >
        <Box
          sx={{ display: "flex", width: "100%", gap: "42px", flexWrap: "wrap" }}
        >
          {currentQuestion.content.variants.map((variant, index) => (
            <FormControl
              key={index}
              disabled={isSending}
              sx={{
                borderRadius: "12px",
                border: `1px solid`,
                borderColor:
                  answer === variant.id
                    ? theme.palette.primary.main
                    : "#9A9AAF",
                overflow: "hidden",
                maxWidth: "317px",
                width: "100%",
                height: "255px",
                background: settings.cfg.design && !quizThemes[settings.cfg.theme].isLight
                    ? "rgba(255,255,255, 0.3)" : settings.cfg.design && quizThemes[settings.cfg.theme].isLight || quizThemes[settings.cfg.theme].isLight
                        ? "#FFFFFF"
                        : "transparent",
                "&:hover": {borderColor: theme.palette.primary.main},
              }}
              // value={index}
              onClick={async (event) => {
                event.preventDefault();
                if (isSending) return;

                setIsSending(true);
                try {
                  await sendAnswer({
                    questionId: currentQuestion.id,
                    body:
                        currentQuestion.content.variants[index].extendedText +
                        " " +
                        currentQuestion.content.variants[index].answer,
                    qid: quizId,
                  });

                  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: quizId,
                    });
                  } catch (e) {
                    enqueueSnackbar("ответ не был засчитан");
                  }
                }

                setIsSending(false);
              }}
            >
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  height: "193px",
                  background: "#ffffff",
                  cursor: "pointer"
                }}
              >
                <Box
                  sx={{
                    width: "100%",
                    display: "flex",
                    justifyContent: "center",
                  }}
                >
                  {variant.extendedText && (
                    <Typography fontSize={"100px"}>
                      {variant.extendedText}
                    </Typography>
                  )}
                </Box>
              </Box>
              <FormControlLabel
                key={variant.id}
                sx={{
                  margin: 0,
                  padding: "15px",
                  color: theme.palette.text.primary,
                  display: "flex",
                  gap: "10px",
                  alignItems:
                    variant.answer.length <= 60 ? "center" : "flex-start",
                  position: "relative",
                  height: "80px",
                  "& .MuiFormControlLabel-label": {
                    wordBreak: "break-word",
                    height: variant.answer.length <= 60 ? undefined : "60px",
                    overflow: "auto",
                    paddingLeft: "45px",
                    "&::-webkit-scrollbar": {
                      width: "4px",
                    },
                    "&::-webkit-scrollbar-thumb": {
                      backgroundColor: "#b8babf",
                    },
                  },
                  "& .MuiFormControlLabel-label.Mui-disabled": {
                    color: theme.palette.text.primary,
                  }
                }}
                value={index}
                control={
                  <Radio
                    checkedIcon={
                      <RadioCheck color={theme.palette.primary.main} />
                    }
                    icon={<RadioIcon />}
                    sx={{
                      position: "absolute",
                      top: "-162px",
                      right: "12px",
                    }}
                  />
                }
                label={
                  <Box sx={{ display: "flex", gap: "10px" }}>
                    <Typography
                      sx={{
                        wordBreak: "break-word",
                        lineHeight: "normal",
                      }}
                    >
                      {variant.answer}
                    </Typography>
                  </Box>
                }
              />
            </FormControl>
          ))}
        </Box>
      </RadioGroup>
    </Box>
  );
};
