import type { QuestionVariant } from "@/model/questionTypes/shared";
import { useQuizSettings } from "@contexts/QuizDataContext";
import { FormControlLabel, Radio, useTheme } from "@mui/material";
import { useQuizViewStore } from "@stores/quizView";
import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import type { MouseEvent } from "react";

type VarimgVariantProps = {
  questionId: string;
  variant: QuestionVariant;
  index: number;
  isSending: boolean;
  setIsSending: (isSending: boolean) => void;
};

export const VarimgVariant = ({ questionId, variant, index, isSending, setIsSending }: VarimgVariantProps) => {
  const { settings } = useQuizSettings();
  const { updateAnswer, deleteAnswer } = useQuizViewStore((state) => state);
  const answers = useQuizViewStore((state) => state.answers);

  const theme = useTheme();

  const { answer } = answers.find((answer) => answer.questionId === questionId) ?? {};

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

    updateAnswer(questionId, variant.id, variant.points || 0);

    if (answer === variant.id) {
      deleteAnswer(questionId);
    }
  };

  return (
    <FormControlLabel
      key={variant.id}
      disabled={isSending}
      sx={{
        marginBottom: "15px",
        borderRadius: "12px",
        padding: "20px",
        color: theme.palette.text.primary,
        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,
        border: `1px solid`,
        borderColor: answer === variant.id ? theme.palette.primary.main : "#9A9AAF",
        display: "flex",
        margin: 0,
        justifyContent: "space-between",
        "&:hover": { borderColor: theme.palette.primary.main },
        "& .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,
        },
      }}
      labelPlacement="start"
      value={index}
      onClick={sendVariant}
      label={variant.answer}
      control={
        <Radio
          checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
          icon={<RadioIcon />}
        />
      }
    />
  );
};
