import { useQuizStore } from "@/stores/useQuizStore";
import type { QuestionVariant } from "@model/questionTypes/shared";
import {
  Checkbox,
  FormControlLabel,
  Input,
  TextField as MuiTextField,
  Radio,
  TextFieldProps,
  TextareaAutosize,
  Typography,
  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 { FC, MouseEvent } from "react";
import { useTranslation } from "react-i18next";

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

interface OwnInputProps {
  questionId: string;
  variant: QuestionVariant;
  largeCheck: boolean;
  ownPlaceholder: string;
}
const OwnInput = ({ questionId, variant, largeCheck, ownPlaceholder }: OwnInputProps) => {
  const theme = useTheme();

  const ownVariants = useQuizViewStore((state) => state.ownVariants);
  const { updateOwnVariant } = useQuizViewStore((state) => state);

  const ownVariantIndex = ownVariants.findIndex((v) => v.id === variant.id);
  const ownAnswer = ownVariantIndex >= 0 ? ownVariants[ownVariantIndex]?.variant.answer || "" : "";

  return largeCheck ? (
    <TextareaAutosize
      placeholder={ownPlaceholder || "|"}
      style={{
        resize: "none",
        width: "100%",
        fontSize: "16px",
        color: ownAnswer.length === 0 ? "ownPlaceholder" : theme.palette.text.primary,
        letterSpacing: "-0.4px",
        wordSpacing: "-3px",
        outline: "0px none",
        backgroundColor: "inherit",
        border: "none",
        //@ts-ignore
        "&::-webkit-scrollbar": {
          width: "4px",
        },
        "&::-webkit-scrollbar-thumb": {
          backgroundColor: theme.palette.primary.main,
        },
        scrollbarColor: theme.palette.primary.main,
      }}
      value={ownAnswer}
      onClick={(e: React.MouseEvent<HTMLTextAreaElement>) => e.stopPropagation()}
      onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => {
        updateOwnVariant(variant.id, e.target.value);
      }}
    />
  ) : (
    <Input
      placeholder={ownPlaceholder || "|"}
      sx={{
        backgroundColor: "inherit",
        width: "100%",
        fontSize: "18px",
        color: ownAnswer.length === 0 ? "ownPlaceholder" : theme.palette.text.primary,
      }}
      value={ownAnswer}
      disableUnderline
      onClick={(e: React.MouseEvent<HTMLElement>) => e.stopPropagation()}
      onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => {
        updateOwnVariant(variant.id, e.target.value);
      }}
    />
  );
};

export const VariantItem = ({
  questionId,
  isMulti,
  variant,
  answer,
  index,
  own = false,
  questionLargeCheck,
  ownPlaceholder,
}: {
  isMulti: boolean;
  questionId: string;
  variant: QuestionVariant;
  answer: string | string[] | undefined;
  index: number;
  own: boolean;
  questionLargeCheck: boolean;
  ownPlaceholder: string;
}) => {
  const { settings } = useQuizStore();
  const theme = useTheme();
  const { updateAnswer, deleteAnswer } = useQuizViewStore((state) => state);
  const { t } = useTranslation();

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

    const variantId = variant.id;

    if (isMulti) {
      const currentAnswer = typeof answer !== "string" ? answer || [] : [];

      return updateAnswer(
        questionId,
        currentAnswer.includes(variantId)
          ? currentAnswer?.filter((item) => item !== variantId)
          : [...currentAnswer, variantId],
        variant.points || 0
      );
    }

    updateAnswer(questionId, variantId, answer === variantId ? 0 : variant.points || 0);

    if (answer === variantId) {
      deleteAnswer(questionId);
    }
  };

  return (
    <FormControlLabel
      key={variant.id}
      sx={{
        position: "relative",
        margin: "0",
        mt: own ? "10px" : "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": {
          width: "100%",
          maxHeight: "100%",
          wordBreak: "break-word",
          height: variant.answer.length <= 60 ? undefined : "60px",
          overflow: "auto",
          lineHeight: "normal",
          "&::-webkit-scrollbar": { width: "4px" },
          "&::-webkit-scrollbar-thumb": { backgroundColor: theme.palette.primary.main },
          scrollbarColor: theme.palette.primary.main,
        },
        "& .MuiFormControlLabel-label.Mui-disabled": {
          color: theme.palette.text.primary,
        },
      }}
      value={index}
      labelPlacement="start"
      control={
        isMulti ? (
          <Radio
            checked={!!answer?.includes(variant.id)}
            checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
            icon={<RadioIcon />}
          />
        ) : (
          <Radio
            checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
            icon={<RadioIcon />}
          />
        )
      }
      label={
        own ? (
          <>
            <Typography
              sx={{
                color: theme.palette.text.primary,
                fontSize: "14px",
                position: "absolute",
                top: "-23px",
              }}
            >
              {t("Enter your answer")}
            </Typography>
            <OwnInput
              questionId={questionId}
              variant={variant}
              largeCheck={questionLargeCheck}
              ownPlaceholder={ownPlaceholder || "|"}
            />
          </>
        ) : (
          variant.answer
        )
      }
      onClick={sendVariant}
    />
  );
};
