import {
  Checkbox,
  FormControlLabel,
  TextField as MuiTextField,
  Radio,
  TextFieldProps,
  useTheme,
} from "@mui/material";
import { enqueueSnackbar } from "notistack";

import { sendAnswer } from "@api/quizRelase";
import { useQuizViewStore } from "@stores/quizView";
import { useQuizData } from "@contexts/QuizDataContext";

import { quizThemes } from "@utils/themes/Publication/themePublication";

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

import type { FC, MouseEvent } from "react";
import type { QuestionVariant } from "@model/questionTypes/shared";
import type { QuizQuestionVariant } from "@model/questionTypes/variant";

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

export const VariantItem = ({
  currentQuestion,
  variant,
  answer,
  index,
  own = false,
  isSending,
  setIsSending,
}: {
  currentQuestion: QuizQuestionVariant;
  variant: QuestionVariant;
  answer: string | string[] | undefined;
  index: number;
  own?: boolean;
  isSending: boolean;
  setIsSending: (a: boolean) => void;
}) => {
  const { settings, quizId, preview } = useQuizData();
  const theme = useTheme();
  const { updateAnswer, deleteAnswer } = useQuizViewStore((state) => state);

  const sendVariant = async (event: MouseEvent<HTMLLabelElement>) => {
    event.preventDefault();

    if (isSending) {
      return;
    }

    setIsSending(true);

    const variantId = currentQuestion.content.variants[index].id;

    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: quizId,
          preview,
        });

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

      setIsSending(false);
      return;
    }

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

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

    if (answer === variantId) {
      try {
        await sendAnswer({
          questionId: currentQuestion.id,
          body: "",
          qid: quizId,
          preview,
        });
      } catch (error) {
        console.log(error);
        enqueueSnackbar("ответ не был засчитан");
      }
      deleteAnswer(currentQuestion.id);
    }

    setIsSending(false);
  };

  return (
    <FormControlLabel
      key={variant.id}
      disabled={isSending}
      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: settings.cfg.design
          ? quizThemes[settings.cfg.theme].isLight
            ? "#FFFFFF"
            : "rgba(255,255,255, 0.3)"
          : quizThemes[settings.cfg.theme].isLight
          ? "white"
          : theme.palette.background.default,
        display: "flex",
        maxWidth: "685px",
        maxHeight: "85px",
        justifyContent: "space-between",
        width: "100%",
        "&:hover": { borderColor: theme.palette.primary.main },
        "&.MuiFormControl-root": { width: "100%" },
        "& .MuiFormControlLabel-label": {
          wordBreak: "break-word",
          height: variant.answer.length <= 60 ? undefined : "60px",
          overflow: "auto",
          lineHeight: "normal",
          "&::-webkit-scrollbar": { width: "4px" },
          "&::-webkit-scrollbar-thumb": { backgroundColor: "#b8babf" },
        },
        "& .MuiFormControlLabel-label.Mui-disabled": {
          color: theme.palette.text.primary,
        },
      }}
      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={sendVariant}
    />
  );
};
