import { Box, ListItem, Typography, useTheme } from "@mui/material";
import { updateQuestion } from "@root/questions/actions";
import { memo } from "react";
import { Draggable } from "react-beautiful-dnd";
import { UntypedQuizQuestion } from "../../../../model/questionTypes/shared";
import QuestionsPageCard from "./QuestionPageCard";

import type { DraggableProvided } from "react-beautiful-dnd";
import { AnyTypedQuizQuestion } from "@frontend/squzanswerer";

type FormDraggableListItemProps = {
  question: AnyTypedQuizQuestion | UntypedQuizQuestion;
  questionIndex: number;
};

type FormItemProps = FormDraggableListItemProps & {
  provided?: DraggableProvided;
};

export const FormItem = ({ question, questionIndex, provided }: FormItemProps) => {
  const theme = useTheme();

  return (
    <>
      {question.deleted ? (
        <Box
          {...provided?.dragHandleProps}
          sx={{
            width: "100%",
            maxWidth: "800px",
            display: "flex",
            justifyContent: "center",
            marginTop: "30px",
            gap: "5px",
          }}
        >
          <Typography
            sx={{
              fontSize: "16px",
              color: theme.palette.grey2.main,
            }}
          >
            Вопрос удалён.
          </Typography>
          <Typography
            onClick={() => {
              updateQuestion(question.id, (question) => {
                question.deleted = false;
              });
            }}
            sx={{
              cursor: "pointer",
              fontSize: "16px",
              textDecoration: "underline",
              color: theme.palette.brightPurple.main,
              textDecorationColor: theme.palette.brightPurple.main,
            }}
          >
            Восстановить?
          </Typography>
        </Box>
      ) : (
        <Box
          sx={{
            width: "100%",
            position: "relative",
            borderBottom: "1px solid rgba(0, 0, 0, 0.23)",
          }}
        >
          <QuestionsPageCard
            key={questionIndex}
            question={question}
            questionIndex={questionIndex}
            draggableProps={provided?.dragHandleProps}
          />
        </Box>
      )}
    </>
  );
};

export const FormDraggableListItem = memo(({ question, questionIndex }: FormDraggableListItemProps) => (
  <Draggable
    draggableId={String(question.id)}
    index={questionIndex}
  >
    {(provided) => (
      <ListItem
        ref={provided.innerRef}
        {...provided.draggableProps}
        sx={{ userSelect: "none", padding: 0 }}
      >
        <FormItem
          question={question}
          questionIndex={questionIndex}
          provided={provided}
        />
      </ListItem>
    )}
  </Draggable>
));

FormDraggableListItem.displayName = "FormDraggableListItem";
