import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import {
  Box,
  Checkbox,
  FormControl,
  FormControlLabel,
  IconButton,
  InputAdornment,
  Paper,
  TextField,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useDebouncedCallback } from "use-debounce";

import { ChooseAnswerModal } from "./ChooseAnswerModal";
import TypeQuestions from "../TypeQuestions";
import SwitchQuestionsPage from "../SwitchQuestionsPage";

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

import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import DeleteIcon from "@icons/questionsPage/deleteIcon";
import OneIcon from "@icons/questionsPage/OneIcon";
import PointsIcon from "@icons/questionsPage/PointsIcon";
import CopyIcon from "@icons/questionsPage/CopyIcon";
import CrossedEyeIcon from "@icons/CrossedEyeIcon";
import HideIcon from "@icons/questionsPage/hideIcon";
import Answer from "@icons/questionsPage/answer";
import OptionsPict from "@icons/questionsPage/options_pict";
import OptionsAndPict from "@icons/questionsPage/options_and_pict";
import Emoji from "@icons/questionsPage/emoji";
import Input from "@icons/questionsPage/input";
import DropDown from "@icons/questionsPage/drop_down";
import Date from "@icons/questionsPage/date";
import Slider from "@icons/questionsPage/slider";
import Download from "@icons/questionsPage/download";
import Page from "@icons/questionsPage/page";
import RatingIcon from "@icons/questionsPage/rating";
import { ReactComponent as PlusIcon } from "../../../assets/icons/plus.svg";

import type { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";

interface Props {
  totalIndex: number;
  draggableProps: DraggableProvidedDragHandleProps | null | undefined;
  isDragging: boolean;
}

const IconAndrom = (isExpanded: boolean, switchState: string) => {
  switch (switchState) {
    case "variant":
      return (
        <Answer
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "images":
      return (
        <OptionsPict
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "varimg":
      return (
        <OptionsAndPict
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "emoji":
      return (
        <Emoji
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "text":
      return (
        <Input
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "select":
      return (
        <DropDown
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "date":
      return (
        <Date
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "number":
      return (
        <Slider
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "file":
      return (
        <Download
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "page":
      return (
        <Page
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    case "rating":
      return (
        <RatingIcon
          color={isExpanded ? "#9A9AAF" : "white"}
          sx={{ height: "22px", width: "20px" }}
        />
      );
    default:
      return <></>;
  }
};
export default function QuestionsPageCard({
  totalIndex,
  draggableProps,
  isDragging,
}: Props) {
  const [plusVisible, setPlusVisible] = useState<boolean>(false);
  const [open, setOpen] = useState<boolean>(false);
  const quizId = Number(useParams().quizId);
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const { listQuestions } = questionStore();
  const { type: switchState, expanded: isExpanded } =
    listQuestions[quizId][totalIndex];
  const anchorRef = useRef(null);
  const debounced = useDebouncedCallback((title) => {
    updateQuestionsList(quizId, totalIndex, { title });
  }, 1000);

  return (
    <>
      <Paper
        id={String(totalIndex)}
        sx={{
          maxWidth: "796px",
          width: "100%",
          borderRadius: "12px",
          backgroundColor: isExpanded ? "white" : "#333647",
        }}
      >
        <Box
          sx={{
            maxWidth: isTablet ? "665px" : "760px",
            display: "flex",
            alignItems: "center",
            gap: isTablet ? "4px" : "10px",
            padding: isMobile ? "20px 20px 0px 20px" : "20px 20px 20px 20px ",
            flexDirection: isMobile ? "column-reverse" : null,
          }}
        >
          <FormControl
            variant="standard"
            sx={{
              p: 0,
              maxWidth: isTablet ? (isMobile ? "100%" : "640px") : "100%",
              width: "100%",
            }}
          >
            <TextField
              defaultValue={listQuestions[quizId][totalIndex].title}
              placeholder={"Заголовок вопроса"}
              onChange={({ target }) => debounced(target.value)}
              InputProps={{
                startAdornment: (
                  <Box>
                    <InputAdornment
                      ref={anchorRef}
                      position="start"
                      sx={{ cursor: "pointer" }}
                      onClick={() => setOpen((isOpened) => !isOpened)}
                    >
                      {IconAndrom(isExpanded, switchState)}
                    </InputAdornment>
                    <ChooseAnswerModal
                      open={open}
                      onClose={() => setOpen(false)}
                      anchorRef={anchorRef}
                      totalIndex={totalIndex}
                    />
                  </Box>
                ),
              }}
              sx={{
                "& .MuiInputBase-root": {
                  color: isExpanded ? "#9A9AAF" : "white",
                  backgroundColor: isExpanded
                    ? theme.palette.background.default
                    : "transparent",
                  height: "48px",
                  borderRadius: "10px",
                  ".MuiOutlinedInput-notchedOutline": {
                    borderWidth: "1px !important",
                  },
                },
              }}
              inputProps={{
                sx: {
                  fontSize: "18px",
                  lineHeight: "21px",
                  py: 0,
                  paddingLeft: switchState.length === 0 ? 0 : "18px",
                },
              }}
            />
          </FormControl>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              width: isMobile ? "100%" : "auto",
              position: "relative",
            }}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
              }}
            >
              <IconButton
                onClick={() =>
                  updateQuestionsList(quizId, totalIndex, {
                    expanded: !isExpanded,
                  })
                }
              >
                {isExpanded ? (
                  <ExpandMoreIcon />
                ) : (
                  <ExpandLessIcon fill="#7E2AEA" />
                )}
              </IconButton>
              {isExpanded ? (
                <></>
              ) : (
                <Box sx={{ display: "flex", borderRight: "solid 1px white" }}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        icon={<HideIcon color={"#7E2AEA"} />}
                        checkedIcon={<CrossedEyeIcon />}
                      />
                    }
                    label={""}
                    sx={{
                      color: theme.palette.grey2.main,
                      ml: "-9px",
                      mr: 0,
                      userSelect: "none",
                    }}
                  />
                  <IconButton onClick={() => copyQuestion(quizId, totalIndex)}>
                    <CopyIcon color={"white"} />
                  </IconButton>
                  <IconButton
                    sx={{
                      cursor: "pointer",
                      borderRadius: "6px",
                      padding: "2px",
                    }}
                    onClick={() => removeQuestion(quizId, totalIndex)}
                  >
                    <DeleteIcon color={"white"} />
                  </IconButton>
                </Box>
              )}

              <OneIcon />
            </Box>
            <IconButton
              sx={{
                position: isMobile ? "absolute" : "relative",
                right: isMobile ? "0" : null,
                bottom: isMobile ? "0" : null,
              }}
              {...draggableProps}
            >
              <PointsIcon />
            </IconButton>
          </Box>
        </Box>
        {isExpanded && (
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              padding: 0,
              borderRadius: "12px",
            }}
          >
            {switchState.length === 0 ? (
              <TypeQuestions totalIndex={totalIndex} />
            ) : (
              <SwitchQuestionsPage totalIndex={totalIndex} />
            )}
          </Box>
        )}
      </Paper>
      <Box
        onMouseEnter={() => setPlusVisible(true)}
        onMouseLeave={() => setPlusVisible(false)}
        sx={{
          maxWidth: "825px",
          display: "flex",
          alignItems: "center",
          height: "40px",
          cursor: "pointer",
        }}
      >
        <Box
          onClick={() => createQuestion(quizId, "", totalIndex + 1)}
          sx={{
            display: plusVisible && !isDragging ? "flex" : "none",
            width: "100%",
            alignItems: "center",
            columnGap: "10px",
          }}
        >
          <Box
            sx={{
              boxSizing: "border-box",
              width: "100%",
              height: "1px",
              backgroundPosition: "bottom",
              backgroundRepeat: "repeat-x",
              backgroundSize: "20px 1px",
              backgroundImage:
                "radial-gradient(circle, #7E2AEA 6px, #F2F3F7 1px)",
            }}
          />
          <PlusIcon />
        </Box>
      </Box>
    </>
  );
}
