import { useState } from "react";
import { useParams } from "react-router-dom";
import { Draggable } from "react-beautiful-dnd";
import {
  Box,
  TextField,
  FormControl,
  InputAdornment,
  IconButton,
  useTheme,
} from "@mui/material";

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

import PointsIcon from "@icons/questionsPage/PointsIcon";
import DeleteIcon from "@icons/questionsPage/deleteIcon";
import MessageIcon from "@icons/messagIcon";
import Popover from "@mui/material/Popover";
import TextareaAutosize from "@mui/base/TextareaAutosize";

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

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

export const AnswerItem = ({
  index,
  totalIndex,
  variants,
  variant,
  icon,
}: AnswerItemProps) => {
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();

  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 onChangeText = (event: ChangeEvent<HTMLInputElement>) => {
    const answerNew = variants.slice();
    answerNew[index].answer = event.target.value;

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

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

    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={{ p: "0 0 20px 0" }}
          >
            <TextField
              value={variant.answer}
              fullWidth
              focused={false}
              placeholder={"Добавьте ответ"}
              onChange={onChangeText}
              onKeyDown={(event: KeyboardEvent<HTMLInputElement>) =>
                event.code === "Enter" && addNewAnswer()
              }
              InputProps={{
                startAdornment: (
                  <>
                    <InputAdornment
                      {...provided.dragHandleProps}
                      position="start"
                    >
                      <PointsIcon />
                    </InputAdornment>
                    {icon && icon}
                  </>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton
                      aria-describedby="my-popover-id"
                      onClick={handleClick}
                    >
                      <MessageIcon />
                    </IconButton>
                    <Popover
                      id="my-popover-id"
                      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": {
                  height: "48px",
                  borderRadius: "10px",
                  background: "#ffffff",
                },
              }}
              inputProps={{
                sx: { fontSize: "18px", lineHeight: "21px", py: 0 },
              }}
            />
          </FormControl>
        </Box>
      )}
    </Draggable>
  );
};
