import { Box, TextField as MuiTextField, TextFieldProps, Typography, useMediaQuery, useTheme } from "@mui/material";
import { updateQuestion } from "@root/questions/actions";
import { FC, useLayoutEffect, useRef, useState } from "react";
import FlagIcon from "@/assets/icons/questionsPage/FlagIcon";
import StarIconMini from "@/assets/icons/questionsPage/StarIconMini";
import HashtagIcon from "@/assets/icons/questionsPage/hashtagIcon";
import HeartIcon from "@/assets/icons/questionsPage/heartIcon";
import LightbulbIcon from "@/assets/icons/questionsPage/lightbulbIcon";
import LikeIcon from "@/assets/icons/questionsPage/likeIcon";
import TropfyIcon from "@/assets/icons/questionsPage/tropfyIcon";
import type { QuizQuestionRating } from "@frontend/squzanswerer";
import ButtonsOptions from "../ButtonsLayout/ButtonsOptions";
import SwitchRating from "./switchRating";

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

interface Props {
  question: QuizQuestionRating;
  openBranchingPage: boolean;
  setOpenBranchingPage: (a: boolean) => void;
}

export type ButtonRatingFrom = {
  name: "star" | "trophie" | "flag" | "heart" | "like" | "bubble" | "hashtag";
  icon: JSX.Element;
};

export default function RatingOptions({ question, openBranchingPage, setOpenBranchingPage }: Props) {
  const [switchState, setSwitchState] = useState("setting");
  const [negativeTextWidth, setNegativeTextWidth] = useState<number>(0);
  const [positiveTextWidth, setPositiveTextWidth] = useState<number>(0);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const negativeRef = useRef<HTMLDivElement>(null);
  const positiveRef = useRef<HTMLDivElement>(null);

  const setNegativeDescription = (value: string) => {
    updateQuestion(question.id, (question) => {
      if (question.type !== "rating") return;

      question.content.ratingNegativeDescription = value.substring(0, 15);
    });
  };

  const setPositiveDescription = (value: string) => {
    updateQuestion(question.id, (question) => {
      if (question.type !== "rating") return;

      question.content.ratingPositiveDescription = value.substring(0, 15);
    });
  };

  useLayoutEffect(() => {
    setNegativeTextWidth(negativeRef.current?.offsetWidth || 0);
  }, [question.content.ratingNegativeDescription]);

  useLayoutEffect(() => {
    setPositiveTextWidth(positiveRef.current?.offsetWidth || 0);
  }, [question.content.ratingPositiveDescription]);

  const buttonRatingForm: ButtonRatingFrom[] = [
    {
      name: "star",
      icon: (
        <StarIconMini
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "trophie",
      icon: (
        <TropfyIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "flag",
      icon: (
        <FlagIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "heart",
      icon: (
        <HeartIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "like",
      icon: (
        <LikeIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "bubble",
      icon: (
        <LightbulbIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
    {
      name: "hashtag",
      icon: (
        <HashtagIcon
          width={isMobile ? (question.content.steps > 5 ? 20 : 32) : 35}
          color={theme.palette.grey2.main}
        />
      ),
    },
  ];

  return (
    <>
      <Box
        sx={{
          display: "flex",
          px: "20px",
          flexDirection: "column",
          gap: "20px",
          marginTop: isMobile ? "20px" : 0,
        }}
      >
        <Box
          sx={{
            width: isMobile ? "auto" : `${question.content.steps * 44}px`,
            maxWidth: "440px",
            display: "flex",
            justifyContent: "space-between",
            padding: "10px 10px 0 10px",
            gap: isMobile ? "8px" : "30px",
          }}
        >
          {Array.from({ length: question.content.steps }, (_, index) => index).map((itemNumber) => (
            <Box
              key={itemNumber}
              {...(itemNumber === 0 || itemNumber === question.content.steps - 1
                ? {
                    onClick: () => {
                      updateQuestion(question.id, (question) => {
                        if (question.type !== "rating") return;

                        question.content.ratingExpanded = true;
                      });
                    },
                    sx: {
                      cursor: "pointer",
                      transform: "scale(1.5)",
                      ":hover": {
                        transform: "scale(1.7)",
                        transition: "0.2s",
                      },
                    },
                  }
                : { sx: { transform: "scale(1.5)" } })}
            >
              {buttonRatingForm.find(({ name }) => question.content.form === name)?.icon}
            </Box>
          ))}
        </Box>
        <Box
          sx={{
            mb: "20px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            maxWidth: "410px",
            width: "100%",
          }}
        >
          <Box sx={{ minWidth: isMobile ? "140px" : "205px" }}>
            <Typography
              ref={negativeRef}
              sx={{
                position: "absolute",
                opacity: 0,
                zIndex: "-100",
                whiteSpace: "nowrap",
                fontSize: "16px",
              }}
            >
              {question.content.ratingNegativeDescription}
            </Typography>
            <TextField
              value={question.content.ratingNegativeDescription}
              placeholder="Негативно"
              onChange={({ target }) => {
                if (target.value.length <= 15) {
                  setNegativeDescription(target.value);
                }
              }}
              onBlur={({ target }) => setNegativeDescription(target.value)}
              sx={{
                width: negativeTextWidth + 10 + "px",
                maxWidth: isMobile ? "140px" : "230px",
                background: "transparent",
                fontSize: "18px",
                minWidth: "95px",
                transition: "0.2s",
                "& .MuiInputBase-root": {
                  "& .MuiInputBase-input": {
                    color: theme.palette.grey2.main,
                    fontSize: "16px",
                    padding: "0 3px",
                    borderRadius: "3px",
                    border: "1px solid",
                    borderColor: "transparent",
                    "&:hover, &:focus": {
                      borderColor: theme.palette.grey2.main,
                    },
                  },
                  "& .MuiOutlinedInput-notchedOutline": {
                    outline: "none",
                    border: "none",
                  },
                },
              }}
            />
          </Box>
          <Box
            sx={{
              minWidth: isMobile ? "140px" : "205px",
              textAlign: isMobile ? "right" : undefined,
            }}
          >
            <Typography
              ref={positiveRef}
              sx={{
                position: "absolute",
                opacity: 0,
                zIndex: "-100",
                whiteSpace: "nowrap",
                fontSize: "16px",
              }}
            >
              {question.content.ratingPositiveDescription}
            </Typography>
            <TextField
              value={question.content.ratingPositiveDescription}
              placeholder="Позитивно"
              onChange={({ target }) => {
                if (target.value.length <= 15) {
                  setPositiveDescription(target.value);
                }
              }}
              onBlur={({ target }) => setPositiveDescription(target.value)}
              sx={{
                width: positiveTextWidth + 10 + "px",
                maxWidth: isMobile ? "140px" : "230px",
                background: "transparent",
                fontSize: "18px",
                minWidth: "95px",
                transition: "0.2s",
                "& .MuiInputBase-root": {
                  "& .MuiInputBase-input": {
                    color: theme.palette.grey2.main,
                    fontSize: "16px",
                    padding: "0 3px",
                    borderRadius: "3px",
                    border: "1px solid",
                    borderColor: "transparent",
                    "&:hover, &:focus": {
                      borderColor: theme.palette.grey2.main,
                    },
                  },
                  "& .MuiOutlinedInput-notchedOutline": {
                    outline: "none",
                    border: "none",
                  },
                },
              }}
            />
          </Box>
        </Box>
      </Box>
      <ButtonsOptions
        switchState={switchState}
        setSwitchState={setSwitchState}
        questionId={question.id}
        questionContentId={question.content.id}
        questionType={question.type}
        questionHasParent={question.content.rule.parentId?.length !== 0}
        setOpenBranchingPage={setOpenBranchingPage}
      />
      <SwitchRating
        switchState={switchState}
        question={question}
      />
    </>
  );
}
