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 { 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 type { ChangeEvent, KeyboardEvent, ReactNode } from "react";
import type { Variants } from "@root/questions";

type AnswerItemProps = {
  index: number;
  totalIndex: number;
  variants: Variants[];
  variant: Variants;
  additionalContent?: ReactNode;
  additionalMobile?: ReactNode;
  icon?: ReactNode;
};

export const AnswerItem = ({
  index,
  totalIndex,
  variants,
  variant,
  additionalContent,
  additionalMobile,
  icon
}: AnswerItemProps) => {
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(790));
  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: isTablet ? " 20px 0 20px 0" : "0 0 18px 0" }}
            // sx={{
            //   margin: isTablet ? " 15px 0 20px 0" : "0 0 20px 0",
            //   borderRadius: "10px",
            //   border: "1px solid rgba(0, 0, 0, 0.23)",
            //   background: "white",
            // }}
          >
            <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 style={{ color: "#9A9AAF", fontSize: "30px" }} />
                    </InputAdornment>
                    {additionalContent}
                  </>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton sx={{ padding: "0" }} aria-describedby="my-popover-id" onClick={handleClick}>
                      <MessageIcon style={{ color: "#9A9AAF", fontSize: "30px", marginRight: "6.5px" }} />
                    </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 sx={{ padding: "0" }} onClick={deleteAnswer}>
                      <DeleteIcon style={{ color: theme.palette.grey2.main, marginRight: "-1px" }} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
              sx={{
                padding: isTablet ? "10px 0px" : 0,
                "& .MuiInputBase-root": {
                  padding: icon ? "5px 13.5px" : "13.5px  13.5px  13.5px  9px",
                  borderRadius: "8px",
                  height: "48px",
                  background: "#ffffff",
                  "& .MuiOutlinedInput-notchedOutline": {
                    border: "none",
                  },
                },
              }}
              inputProps={{
                sx: { fontSize: "18px", lineHeight: "21px", py: 0, ml: "13px" },
              }}
            />
            {additionalMobile}
          </FormControl>
        </Box>
      )}
    </Draggable>
  );
};
