import type { QuestionVariant } from "@/model/questionTypes/shared";
import { useQuizStore } from "@/stores/useQuizStore";
import { useQuizViewStore, type OwnVariant } from "@stores/quizView";
import {
  Box,
  Checkbox,
  FormControl,
  FormControlLabel,
  Input,
  Radio,
  TextareaAutosize,
  Typography,
  useTheme,
} from "@mui/material";
import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { polyfillCountryFlagEmojis } from "country-flag-emoji-polyfill";
import type { MouseEvent } from "react";
import { useTranslation } from "react-i18next";
import { useEffect } from "react";
import { OwnEmojiPicker } from "./OwnEmojiPicker";

polyfillCountryFlagEmojis();

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

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: OwnVariant) => v.id === variant.id);
  const ownAnswer = ownVariantIndex >= 0 ? ownVariants[ownVariantIndex]?.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,
          overflow: "auto",
        }}
        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 EmojiVariant = ({
  answer,
  variant,
  index,
  questionId,
  isMulti,
  own,
  questionLargeCheck,
  ownPlaceholder,
}: EmojiVariantProps) => {
  const { settings } = useQuizStore();
  const { updateAnswer, deleteAnswer, updateOwnVariant, ownVariants } = useQuizViewStore((state) => state);
  const theme = useTheme();
  const { t } = useTranslation();

  const customEmoji = ownVariants.find((v: OwnVariant) => v.id === variant.id)?.variant.extendedText || "";

  const onVariantClick = async (event: MouseEvent<HTMLDivElement>) => {
    event.preventDefault();
    const variantId = variant.id;

    if (isMulti) {
      const currentAnswer = Array.isArray(answer) ? answer : [];
      const newAnswer = currentAnswer.includes(variantId)
        ? currentAnswer.filter((item) => item !== variantId)
        : [...currentAnswer, variantId];
      updateAnswer(questionId, newAnswer, variant.points || 0);
    } else {
      if (answer === variant.id) {
        deleteAnswer(questionId);
      } else {
        updateAnswer(questionId, variant.id, variant.points || 0);
      }
    }
  };

  const handleEmojiSelect = (emoji: string) => {
    // We store custom emoji in ownVariants store, with a specific field to differentiate
    const currentOwnAnswer = ownVariants.find((v: OwnVariant) => v.id === variant.id)?.variant.answer || "";
    updateOwnVariant(variant.id, currentOwnAnswer, emoji);
  };

  const handleEmojiRemove = () => {
    // Сохраняем текущий answer, очищаем только extendedText (эмодзи)
    const currentOwnAnswer = ownVariants.find((v: OwnVariant) => v.id === variant.id)?.variant.answer || "";
    updateOwnVariant(variant.id, currentOwnAnswer, "");
  };

  const isSelected = isMulti ? Array.isArray(answer) && answer.includes(variant.id) : answer === variant.id;

  return (
    <FormControl
      key={index}
      sx={{
        borderRadius: "12px",
        border: `1px solid`,
        borderColor: isSelected ? 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 },
      }}
      onClick={onVariantClick}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          height: "193px",
          background: "#ffffff",
          cursor: "pointer",
        }}
      >
        {own ? (
          <OwnEmojiPicker
            emoji={customEmoji || variant.extendedText}
            onEmojiSelect={handleEmojiSelect}
            onEmojiRemove={customEmoji ? handleEmojiRemove : undefined}
          />
        ) : (
          <Box
            sx={{
              width: "100%",
              display: "flex",
              justifyContent: "center",
            }}
          >
            {variant.extendedText && <Typography fontSize="100px">{variant.extendedText}</Typography>}
          </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,
          margin: 0,
          padding: "15px",
          display: "flex",
          alignItems: variant.answer.length <= 60 ? "center" : "flex-start",
          position: "relative",
          height: "80px",
          justifyContent: "center",
          "& .MuiFormControlLabel-label": {
            wordBreak: "break-word",
            height: variant.answer.length <= 60 ? "100%" : "60px",
            overflow: "auto",
            "&::-webkit-scrollbar": { width: "4px" },
            "&::-webkit-scrollbar-thumb": {
              backgroundColor: theme.palette.primary.main,
            },
            scrollbarColor: theme.palette.primary.main,
            width: "100%",
          },
          "& .MuiFormControlLabel-label.Mui-disabled": {
            color: theme.palette.text.primary,
          },
        }}
        value={index}
        control={
          isMulti ? (
            <Checkbox
              checked={isSelected}
              checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
              icon={<RadioIcon />}
              sx={{ position: "absolute", top: "-162px", right: "12px" }}
            />
          ) : (
            <Radio
              checked={isSelected}
              checkedIcon={<RadioCheck color={theme.palette.primary.main} />}
              icon={<RadioIcon />}
              sx={{ position: "absolute", top: "-162px", right: "12px" }}
            />
          )
        }
        label={
          own ? (
            <OwnInput
              questionId={questionId}
              variant={variant}
              largeCheck={questionLargeCheck}
              ownPlaceholder={ownPlaceholder || "|"}
            />
          ) : (
            <Box sx={{ display: "flex", gap: "10px" }}>
              <Typography sx={{ wordBreak: "break-word", lineHeight: "normal" }}>{variant.answer}</Typography>
            </Box>
          )
        }
      />
    </FormControl>
  );
};
