import type { QuestionVariant, QuestionVariantWithEditedImages } from "@/model/questionTypes/shared";
import { Box, Checkbox, FormControlLabel, Input, Radio, 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 { useMemo, type MouseEvent, useRef, useEffect } from "react";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import { useQuizStore } from "@/stores/useQuizStore";
import { useTranslation } from "react-i18next";
import { OwnImage } from "./OwnImage";
import { useSnackbar } from "notistack";

type ImagesProps = {
  questionId: string;
  variant: QuestionVariantWithEditedImages;
  index: number;
  answer: string | string[] | undefined;
  isMulti: boolean;
  own: boolean;
  questionLargeCheck: boolean;
  ownPlaceholder: string;
};

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

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

  return largeCheck ? (
    <Box sx={{ overflow: "auto" }}>
      <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);
        }}
      />
    </Box>
  ) : (
    <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 ImageVariant = ({
  questionId,
  answer,
  isMulti,
  variant,
  index,
  own,
  questionLargeCheck,
  ownPlaceholder,
}: ImagesProps) => {
  const { settings } = useQuizStore();
  const { deleteAnswer, updateAnswer } = useQuizViewStore((state) => state);
  const theme = useTheme();
  const { t } = useTranslation();
  const isMobile = useRootContainerSize() < 450;
  const isTablet = useRootContainerSize() < 850;
  const { enqueueSnackbar } = useSnackbar();

  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  const onVariantClick = async (event: MouseEvent<HTMLDivElement>) => {
    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, variant.points || 0);

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

  const choiceImgUrl = useMemo(() => {
    if (variant.editedUrlImagesList !== undefined && variant.editedUrlImagesList !== null) {
      return variant.editedUrlImagesList[isMobile ? "mobile" : isTablet ? "tablet" : "desktop"];
    } else {
      return variant.extendedText;
    }
  }, []);

  useEffect(() => {
    if (canvasRef.current !== null) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext("2d");
      if (ctx !== null) {
        const img = new Image();
        img.src = choiceImgUrl;

        img.onload = () => {
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        };
      }
    }
  }, []);

  return (
    <Box
      sx={{
        position: "relative",
        cursor: "pointer",
        borderRadius: "12px",
        border: `1px solid`,
        borderColor: !!answer?.includes(variant.id) ? theme.palette.primary.main : "#9A9AAF",
        "&:hover": { borderColor: theme.palette.primary.main },
        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",
      }}
      onClick={onVariantClick}
    >
      <Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
        <Box sx={{ width: "100%", height: "300px" }}>
          {own ? (
            <OwnImage
              imageUrl={choiceImgUrl}
              questionId={questionId}
              variantId={variant.id}
              onValidationError={(errorType) => {
                enqueueSnackbar(errorType === "size" ? t("file is too big") : t("file type is not supported"), {
                  variant: "warning",
                });
              }}
            />
          ) : (
            variant.extendedText && (
              <canvas
                ref={canvasRef}
                style={{
                  display: "block",
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                  borderRadius: "12px 12px 0 0",
                }}
              />
            )
          )}
        </Box>
      </Box>
      {own && (
        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: "14px",
            pl: "15px",
          }}
        >
          {t("Enter your answer")}
        </Typography>
      )}
      <FormControlLabel
        key={variant.id}
        sx={{
          textAlign: "center",
          color: theme.palette.text.primary,
          marginTop: "10px",
          marginLeft: 0,
          padding: "10px",
          display: "flex",
          alignItems: variant.answer.length <= 60 ? "center" : "flex-start",
          justifyContent: "center",
          position: "relative",
          height: "80px",
          "& .MuiFormControlLabel-label": {
            wordBreak: "break-word",
            height: variant.answer.length <= 60 ? undefined : "60px",
            lineHeight: "normal",
            overflow: "auto",
            maxHeight: "100%",
            width: "100%",
            "&::-webkit-scrollbar": {
              width: "4px",
            },
            "&::-webkit-scrollbar-thumb": {
              backgroundColor: theme.palette.primary.main,
            },
            scrollbarColor: theme.palette.primary.main,
          },
        }}
        value={index}
        control={
          isMulti ? (
            <Checkbox
              checked={!!answer?.includes(variant.id)}
              checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
              icon={<RadioIcon />}
              sx={{
                position: "absolute",
                top: "-297px",
                right: 0,
              }}
            />
          ) : (
            <Radio
              checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
              icon={<RadioIcon />}
              sx={{
                position: "absolute",
                top: "-297px",
                right: 0,
              }}
            />
          )
        }
        label={
          own ? (
            <OwnInput
              questionId={questionId}
              variant={variant}
              largeCheck={questionLargeCheck}
              ownPlaceholder={ownPlaceholder || "|"}
            />
          ) : (
            variant.answer
          )
        }
      />
    </Box>
  );
};
