import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import { Draggable } from "react-beautiful-dnd";
import {
  Box,
  TextField,
  FormControl,
  InputAdornment,
  IconButton,
  Popover,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import { useDebouncedCallback } from "use-debounce";
import { EmojiPicker } from "@ui_kit/EmojiPicker";

import { questionStore, updateQuestionsList } from "@root/questions";

import PointsIcon from "@icons/questionsPage/PointsIcon";
import DeleteIcon from "@icons/questionsPage/deleteIcon";
import MessageIcon from "@icons/messagIcon";
import TextareaAutosize from "@mui/base/TextareaAutosize";
import AddEmoji from "../../../assets/icons/questionsPage/addEmoji";

import type { ChangeEvent, KeyboardEvent } from "react";
import type { Variants } from "@root/questions";

type AnswerItemProps = {
  index: number;
  totalIndex: number;
  variants: Variants[];
  variant: Variants;
  emoji: boolean;
};

export const AnswerItem = ({
  index,
  totalIndex,
  variants,
  variant,
  emoji,
}: AnswerItemProps) => {
  const [open, setOpen] = useState<boolean>(false);
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const anchorElement = useRef();
  const debounced = useDebouncedCallback((value) => {
    const answerNew = variants.slice();
    answerNew[index].answer = value;

    updateQuestionsList(quizId, totalIndex, {
      content: {
        ...listQuestions[quizId][totalIndex].content,
        variants: answerNew,
      },
    });
  }, 1000);

  const [isOpen, setIsOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
    setIsOpen(true);
  };

  const handleClose = () => {
    setIsOpen(false);
  };

  const addNewAnswer = () => {
    const answerNew = variants.slice();
    answerNew.push({ answer: "", hints: "", emoji: "" });

    updateQuestionsList(quizId, totalIndex, {
      content: {
        ...listQuestions[quizId][totalIndex].content,
        variants: answerNew,
      },
    });
  };

  const deleteAnswer = () => {
    const answerNew = variants.slice();
    answerNew.splice(index, 1);

    updateQuestionsList(quizId, totalIndex, {
      content: {
        ...listQuestions[quizId][totalIndex].content,
        variants: answerNew,
      },
    });
  };

  const changeAnswerHint = (event: ChangeEvent<HTMLTextAreaElement>) => {
    const answerNew = variants.slice();
    answerNew[index].hints = event.target.value;

    updateQuestionsList(quizId, totalIndex, {
      content: {
        ...listQuestions[quizId][totalIndex].content,
        variants: answerNew,
      },
    });
  };

  return (
    <Draggable draggableId={String(index)} index={index}>
      {(provided) => (
        <Box ref={provided.innerRef} {...provided.draggableProps}>
          <FormControl
            key={index}
            fullWidth
            variant="standard"
            sx={{ padding: isMobile ? " 15px 0 20px 0" : "0 0 20px 0" }}
          >
            <TextField
              defaultValue={variant.answer}
              fullWidth
              focused={false}
              placeholder={"Добавьте ответ"}
              multiline={listQuestions[quizId][totalIndex].content.largeCheck}
              onChange={({ target }) => debounced(target.value)}
              onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
                if (
                  event.code === "Enter" &&
                  !listQuestions[quizId][totalIndex].content.largeCheck
                ) {
                  addNewAnswer();
                }
              }}
              InputProps={{
                startAdornment: (
                  <>
                    <InputAdornment
                      {...provided.dragHandleProps}
                      position="start"
                    >
                      <PointsIcon />
                    </InputAdornment>
                    {emoji && (
                      <Box sx={{ cursor: "pointer", margin: "0 15px 0 5px" }}>
                        <Box ref={anchorElement} onClick={() => setOpen(true)}>
                          <Box
                            sx={{
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                              gap: "5px",
                            }}
                          >
                            {variant.emoji && (
                              <Box sx={{ width: "30px" }}>{variant.emoji}</Box>
                            )}
                            <AddEmoji />
                          </Box>
                        </Box>
                        <Popover
                          open={open}
                          anchorEl={anchorElement.current}
                          onClose={() => setOpen(false)}
                          anchorOrigin={{
                            vertical: "bottom",
                            horizontal: "right",
                          }}
                          sx={{
                            ".MuiPaper-root.MuiPaper-rounded": {
                              background: "transparent",
                            },
                          }}
                        >
                          <EmojiPicker
                            onEmojiSelect={({ native }) => {
                              setOpen(false);
                              const cloneVariants = [...variants];

                              cloneVariants[index] = {
                                ...cloneVariants[index],
                                emoji: native,
                              };

                              updateQuestionsList(quizId, totalIndex, {
                                content: {
                                  ...listQuestions[quizId][totalIndex].content,
                                  variants: cloneVariants,
                                },
                              });
                            }}
                          />
                        </Popover>
                      </Box>
                    )}
                  </>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={handleClick}>
                      <MessageIcon />
                    </IconButton>
                    <Popover
                      open={isOpen}
                      anchorEl={anchorEl}
                      onClose={handleClose}
                      anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
                    >
                      <TextareaAutosize
                        style={{ margin: "10px" }}
                        placeholder="Подсказка для этого ответа"
                        value={variant.hints}
                        onChange={changeAnswerHint}
                        onKeyDown={(
                          event: KeyboardEvent<HTMLTextAreaElement>
                        ) => event.stopPropagation()}
                      />
                    </Popover>
                    <IconButton onClick={deleteAnswer}>
                      <DeleteIcon color={theme.palette.grey2.main} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
              sx={{
                "& .MuiInputBase-root": {
                  padding: emoji ? "5px 13.5px" : "13.5px",
                  borderRadius: "10px",
                  background: "#ffffff",
                },
              }}
              inputProps={{
                sx: { fontSize: "18px", lineHeight: "21px", py: 0 },
              }}
            />
          </FormControl>
        </Box>
      )}
    </Draggable>
  );
};
