import { AnyTypedQuizQuestion } from "@frontend/squzanswerer";
import { ArrowDownIcon } from "@icons/questionsPage/ArrowDownIcon";
import { CopyIcon } from "@icons/questionsPage/CopyIcon";
import { PointsIcon } from "@icons/questionsPage/PointsIcon";
import Answer from "@icons/questionsPage/answer";
import Date from "@icons/questionsPage/date";
import { DeleteIcon } from "@icons/questionsPage/deleteIcon";
import Download from "@icons/questionsPage/download";
import DropDown from "@icons/questionsPage/drop_down";
import Emoji from "@icons/questionsPage/emoji";
import Input from "@icons/questionsPage/input";
import OptionsAndPict from "@icons/questionsPage/options_and_pict";
import OptionsPict from "@icons/questionsPage/options_pict";
import Page from "@icons/questionsPage/page";
import RatingIcon from "@icons/questionsPage/rating";
import Slider from "@icons/questionsPage/slider";
import { QuestionType } from "@model/question/question";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import {
  Box,
  FormControl,
  IconButton,
  InputAdornment,
  TextField as MuiTextField,
  Paper,
  TextFieldProps,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  copyQuestion,
  deleteQuestion,
  deleteQuestionWithTimeout,
  toggleExpandQuestion,
  updateQuestion,
  updateUntypedQuestion,
} from "@root/questions/actions";
import { FC, useRef, useState } from "react";
import type { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import type { UntypedQuizQuestion } from "../../../../model/questionTypes/shared";
import SwitchQuestionsPage from "../../SwitchQuestionsPage";
import FormTypeQuestions from "../FormTypeQuestions";
import { ChooseAnswerModal } from "./ChooseAnswerModal";

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

interface Props {
  question: AnyTypedQuizQuestion | UntypedQuizQuestion;
  questionIndex: number;
  draggableProps: DraggableProvidedDragHandleProps | null | undefined;
}

export default function QuestionsPageCard({ question, questionIndex, draggableProps }: Props) {
  const maxLengthTextField = 225;
  const [open, setOpen] = useState<boolean>(false);
  const [isTextFieldtActive, setIsTextFieldtActive] = useState(false);
  const anchorRef = useRef(null);
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(790));

  const setTitle = (title: string) => {
    const updateQuestionFn = question.type === null ? updateUntypedQuestion : updateQuestion;

    updateQuestionFn(question.id, (question) => {
      question.title = title;
    });
  };

  const handleInputFocus = () => {
    setIsTextFieldtActive(true);
  };

  const handleInputBlur = (event: React.FocusEvent<HTMLInputElement>) => {
    setIsTextFieldtActive(false);
  };

  return (
    <>
      <Paper
        sx={{
          overflow: "hidden",
          maxWidth: "796px",
          width: "100%",
          backgroundColor: question.expanded ? "white" : "#EEE4FC",
          border: question.expanded ? "none" : "1px solid #9A9AAF",
          boxShadow: "none",
          paddingBottom: "20px",
          borderRadius: "0",
          borderTopLeftRadius: questionIndex == 0 ? "12px" : 0,
          borderTopRightRadius: questionIndex == 0 ? "12px" : 0,
        }}
      >
        <Box
          sx={{
            display: "flex",
            p: 0,
            flexDirection: "column",
          }}
        >
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              margin: "20px",
              gap: "18px",
              flexDirection: isMobile ? "column-reverse" : null,
            }}
          >
            <FormControl
              variant="standard"
              sx={{
                p: 0,
                maxWidth: isTablet ? "549px" : "640px",
                width: "100%",
                marginRight: isMobile ? "0px" : "16.1px",
              }}
            >
              <TextField
                placeholder={`Заголовок ${questionIndex + 1} вопроса`}
                value={question.title}
                onChange={({ target }) => {
                  if (target.value.length <= 225) setTitle(target.value);
                }}
                onFocus={handleInputFocus}
                onBlur={handleInputBlur}
                sx={{
                  width: "100%",
                  margin: isMobile ? "10px 0" : 0,
                  "& .MuiInputBase-root": {
                    color: "#000000",
                    backgroundColor: question.expanded ? theme.palette.background.default : "transparent",
                    height: "48px",
                    borderRadius: "10px",
                    ".MuiOutlinedInput-notchedOutline": {
                      borderWidth: "1px !important",
                      border: !question.expanded ? "none" : null,
                    },
                    "& .MuiInputBase-input::placeholder": {
                      color: "#4D4D4D",
                      opacity: 0.8,
                    },
                  },
                }}
                inputProps={{
                  maxLength: maxLengthTextField,
                }}
                InputProps={{
                  startAdornment: (
                    <Box>
                      <InputAdornment
                        ref={anchorRef}
                        position="start"
                        sx={{ cursor: "pointer" }}
                        onClick={() => setOpen((isOpened) => !isOpened)}
                      >
                        {IconAndrom(question.type)}
                      </InputAdornment>
                      <ChooseAnswerModal
                        open={open}
                        onClose={() => setOpen(false)}
                        anchorRef={anchorRef}
                        question={question}
                        questionType={question.type}
                      />
                    </Box>
                  ),
                  endAdornment: isTextFieldtActive && question.title.length >= maxLengthTextField - 7 && (
                    <Box
                      sx={{
                        display: "flex",
                        marginTop: "5px",
                        marginLeft: "auto",
                        position: "absolute",
                        bottom: "-28px",
                        right: "0",
                      }}
                    >
                      <Typography fontSize="14px">{question.title.length}</Typography>
                      <span>/</span>
                      <Typography fontSize="14px">{maxLengthTextField}</Typography>
                    </Box>
                  ),
                }}
              />
            </FormControl>
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                width: isMobile ? "100%" : "auto",
                position: "relative",
              }}
            >
              <Box
                sx={{
                  flexDirection: isMobile ? "row-reverse" : null,
                  display: "flex",
                  alignItems: "center",
                  gap: "4px",
                }}
              >
                <IconButton
                  sx={{ padding: "0", margin: "5px" }}
                  disableRipple
                  data-cy="expand-question"
                  onClick={() => toggleExpandQuestion(question.id)}
                >
                  {question.expanded ? (
                    <ArrowDownIcon
                      style={{
                        width: "18px",
                        color: "#4D4D4D",
                      }}
                    />
                  ) : (
                    <ExpandLessIcon
                      sx={{
                        boxSizing: "border-box",
                        fill: theme.palette.brightPurple.main,
                        background: "#FFF",
                        borderRadius: "6px",
                        height: "30px",
                        width: "30px",
                      }}
                    />
                  )}
                </IconButton>

                {question.expanded ? (
                  <></>
                ) : (
                  <Box
                    sx={{
                      display: "flex",
                      height: "30px",
                      borderRight: "solid 1px #4D4D4D",
                    }}
                  >
                    <IconButton
                      sx={{ padding: "0" }}
                      onClick={() => copyQuestion(question.id, question.quizId)}
                    >
                      <CopyIcon style={{ color: theme.palette.brightPurple.main }} />
                    </IconButton>
                    {questionIndex > 0 && (
                      <IconButton
                        sx={{
                          cursor: "pointer",
                          borderRadius: "6px",
                          padding: "0",
                          margin: "0 5px 0 10px",
                        }}
                        onClick={() => {
                          deleteQuestionWithTimeout(question.id, () => deleteQuestion(question.id));
                        }}
                      >
                        <DeleteIcon style={{ color: theme.palette.brightPurple.main }} />
                      </IconButton>
                    )}
                  </Box>
                )}

                <Box
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    height: "30px",
                    width: "30px",
                    marginLeft: "3px",
                    borderRadius: "50%",
                    fontSize: "16px",
                    color: question.expanded ? theme.palette.brightPurple.main : "#FFF",
                    background: question.expanded ? "#EEE4FC" : theme.palette.brightPurple.main,
                  }}
                >
                  {questionIndex + 1}
                </Box>
              </Box>

              {draggableProps && (
                <IconButton
                  disableRipple
                  sx={{
                    padding: isMobile ? "0" : "0 5px",
                    right: isMobile ? "0" : null,
                    bottom: isMobile ? "0" : null,
                  }}
                  {...draggableProps}
                >
                  <PointsIcon style={{ color: "#4D4D4D", fontSize: "30px" }} />
                </IconButton>
              )}
            </Box>
          </Box>
          {question.expanded && (
            <>
              {question.type === null ? (
                <FormTypeQuestions question={question} />
              ) : (
                <SwitchQuestionsPage question={question} />
              )}
            </>
          )}
        </Box>
      </Paper>
    </>
  );
}

const IconAndrom = (questionType: QuestionType | null) => {
  switch (questionType) {
    case "variant":
      return (
        <Answer
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "images":
      return (
        <OptionsPict
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "varimg":
      return (
        <OptionsAndPict
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "emoji":
      return (
        <Emoji
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "text":
      return (
        <Input
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "select":
      return (
        <DropDown
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "date":
      return (
        <Date
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "number":
      return (
        <Slider
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "file":
      return (
        <Download
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "page":
      return (
        <Page
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "rating":
      return (
        <RatingIcon
          color="#9A9AAF"
          sx={{ height: "22px", width: "20px" }}
        />
      );
    default:
      return null;
  }
};
