import { PointsIcon } from "@icons/questionsPage/PointsIcon";
import { DeleteIcon } from "@icons/questionsPage/deleteIcon";
import {
  Box,
  FormControl,
  IconButton,
  InputAdornment,
  TextField as MuiTextField,
  TextFieldProps,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { addQuestionVariant, deleteQuestionVariant, setQuestionVariantField, updateQuestion } from "@root/questions/actions";
import { enqueueSnackbar } from "notistack";
import { memo, type ChangeEvent, type FC, type KeyboardEvent, type ReactNode } from "react";
import { Draggable } from "react-beautiful-dnd";
import type { QuestionVariant, QuizQuestionVariant } from "@frontend/squzanswerer";

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

type AnswerItemProps = {
  index: number;
  questionId: string;
  variant: QuestionVariant;
  largeCheck?: boolean;
  disableKeyDown?: boolean;
  additionalContent?: ReactNode;
  additionalMobile?: ReactNode;
  isOwn: boolean;
};

const AnswerItem = memo<AnswerItemProps>(
  ({ index, variant, questionId, largeCheck = false, additionalContent, additionalMobile, disableKeyDown, isOwn }) => {
    const theme = useTheme();
    const isTablet = useMediaQuery(theme.breakpoints.down(790));

    return (
      <Draggable
        draggableId={String(index)}
        index={index}
      >
        {(provided) => (
          <Box
            ref={provided.innerRef}
            {...provided.draggableProps}
          >
            <FormControl
              key={index}
              fullWidth
              variant="standard"
              sx={{
                margin: isTablet ? " 15px 0 20px 0" : "0 0 15px 0",
                borderRadius: "10px",
                border: "1px solid rgba(0, 0, 0, 0.23)",
                background: "white",
              }}
            >
              <TextField
                value={variant.answer}
                fullWidth
                focused={false}
                placeholder={isOwn ? "Добавьте текст-подсказку для ввода “своего ответа”" : "Добавьте ответ"}
                multiline={largeCheck}
                onChange={({ target }: ChangeEvent<HTMLInputElement>) => {
                  if (target.value.length <= 1000) {
                    setQuestionVariantField(questionId, variant.id, "answer", target.value || " ");
                  }
                }}
                onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
                  if (disableKeyDown) {
                    enqueueSnackbar("100 максимальное количество");
                  } else if (event.code === "Enter" && !largeCheck) {
                    addQuestionVariant(questionId);
                  }
                }}
                InputProps={{
                  startAdornment: (
                    <>
                      <InputAdornment
                        {...provided.dragHandleProps}
                        position="start"
                      >
                        <PointsIcon style={{ color: "#9A9AAF", fontSize: "30px" }} />
                      </InputAdornment>
                      {additionalContent}
                    </>
                  ),
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        sx={{ padding: "0" }}
                        onClick={() => {
                          isOwn ? updateQuestion<QuizQuestionVariant>(questionId, (question) => {
                            question.content.own = false;
                          })
                           : 
                           deleteQuestionVariant(questionId, variant.id)
                        }}
                      >
                        <DeleteIcon
                          style={{
                            color: theme.palette.grey2.main,
                            marginRight: "-1px",
                          }}
                        />
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
                sx={{
                  "& .MuiInputBase-root": {
                    padding: additionalContent ? "5px 13px" : "13px",
                    borderRadius: "10px",
                    background: isOwn ? "#F2F3F7" : "white",
                    "& input.MuiInputBase-input": {
                      height: "22px",
                    },
                    "& textarea.MuiInputBase-input": {
                      marginTop: "1px",
                    },
                    "& .MuiOutlinedInput-notchedOutline": {
                      border: "none",
                    },
                  },
                }}
                inputProps={{
                  sx: {
                    fontSize: "18px",
                    lineHeight: "21px",
                    py: 0,
                    ml: "13px",
                  },
                  "data-cy": "quiz-variant-question-answer",
                }}
              />
              {additionalMobile}
            </FormControl>
          </Box>
        )}
      </Draggable>
    );
  }
);

AnswerItem.displayName = "AnswerItem";

export default AnswerItem;
