import {
  Box,
  TextField as MuiTextField,
  TextFieldProps,
  Typography,
  useTheme,
} from "@mui/material";

import CustomTextField from "@ui_kit/CustomTextField";

import { updateAnswer, useQuizViewStore } from "@stores/quizView";

import { sendAnswer } from "@api/quizRelase";
import { useQuizData } from "@contexts/QuizDataContext";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import { enqueueSnackbar } from "notistack";
import { ChangeEvent, FC, useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import type { QuizQuestionText } from "../../../model/questionTypes/text";

const TextField = MuiTextField as unknown as FC<TextFieldProps>; // temporary fix ts(2590)

type TextProps = {
  currentQuestion: QuizQuestionText;
  stepNumber: number | null;
};

const Orientation = [
  { horizontal: true },
  { horizontal: false },
  { horizontal: true },
  { horizontal: true },
  { horizontal: false },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: false },
  { horizontal: true },
  { horizontal: false },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: false },
  { horizontal: false },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
  { horizontal: true },
];

export const Text = ({ currentQuestion, stepNumber }: TextProps) => {
  const theme = useTheme();
  const { settings } = useQuizData();
  const spec = settings.cfg.spec;
  const { quizId } = useQuizData();
  const { answers } = useQuizViewStore();
  const isMobile = useRootContainerSize() < 650;
  const { answer } =
    answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};
  const [isSending, setIsSending] = useState<boolean>(false);

  const inputHC = useDebouncedCallback(async (text) => {
    setIsSending(true);
    try {
      await sendAnswer({
        questionId: currentQuestion.id,
        body: text,
        qid: quizId,
      });
    } catch (e) {
      enqueueSnackbar("ответ не был засчитан");
    }

    setIsSending(false);
  }, 400);
  useEffect(
    () => () => {
      inputHC.flush();
    },
    [inputHC]
  );
  switch (spec) {
    case true:
      return (
        <TextSpecial
          currentQuestion={currentQuestion}
          answer={answer}
          inputHC={inputHC}
          stepNumber={stepNumber}
        />
      );
    case undefined:
      return (
        <TextNormal
          currentQuestion={currentQuestion}
          answer={answer}
          inputHC={inputHC}
        />
      );
    default:
      return (
        <TextNormal
          currentQuestion={currentQuestion}
          answer={answer}
          inputHC={inputHC}
        />
      );
  }
};

interface Props {
  currentQuestion: QuizQuestionText;
  answer: any;
  inputHC: (a: string) => void;
  stepNumber?: number | null;
}

const TextNormal = ({ currentQuestion, answer, inputHC }: Props) => {
  const isMobile = useRootContainerSize() < 650;
  const theme = useTheme();
  const { settings } = useQuizData();

  return (
    <Box>
      <Typography
        variant="h5"
        color={theme.palette.text.primary}
        sx={{ wordBreak: "break-word" }}
      >
        {currentQuestion.title}
      </Typography>
      <Box
        sx={{
          display: "flex",
          width: "100%",
          marginTop: "20px",
          flexDirection: isMobile ? "column-reverse" : undefined,
          alignItems: "center",
        }}
      >
        <CustomTextField
          placeholder={currentQuestion.content.placeholder}
          value={answer || ""}
          onChange={async ({ target }) => {
            updateAnswer(currentQuestion.id, target.value, 0);
            inputHC(target.value);
          }}
          sx={{
            "& .MuiOutlinedInput-root": {
              backgroundColor: settings.cfg.design
                ? "rgba(154,154,175, 0.2)"
                : "#FFFFFF",
            },
            "&:focus-visible": { borderColor: theme.palette.primary.main },
          }}
        />
        {currentQuestion.content.back &&
          currentQuestion.content.back !== " " && (
            <Box
              sx={{
                maxWidth: "400px",
                width: "100%",
                height: "300px",
                margin: "15px",
              }}
            >
              <img
                key={currentQuestion.id}
                src={currentQuestion.content.back}
                style={{ width: "100%", height: "100%", objectFit: "cover" }}
                alt=""
              />
            </Box>
          )}
      </Box>
    </Box>
  );
};

const TextSpecial = ({
  currentQuestion,
  answer,
  inputHC,
  stepNumber,
}: Props) => {
  const theme = useTheme();
  const isMobile = useRootContainerSize() < 650;
  const isHorizontal = Orientation[Number(stepNumber) - 1].horizontal;
  const { settings } = useQuizData();

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: isMobile ? "column" : undefined,
        alignItems: isMobile ? "center" : undefined,
      }}
    >
      <Box
        sx={{
          display: "flex",
          width: "100%",
          marginTop: "20px",
          flexDirection: "column",
          alignItems: "center",
          gap: "20px",
        }}
      >
        <Typography
          variant="h5"
          color={theme.palette.text.primary}
          sx={{ wordBreak: "break-word" }}
        >
          {currentQuestion.title}
        </Typography>
        {isHorizontal &&
          currentQuestion.content.back &&
          currentQuestion.content.back !== " " && (
            <Box sx={{ margin: "30px", width: "50vw", maxHeight: "550px" }}>
              <img
                key={currentQuestion.id}
                src={currentQuestion.content.back}
                style={{ width: "100%", height: "100%", objectFit: "cover" }}
                alt=""
              />
            </Box>
          )}
        {
          <TextField
            autoFocus={true}
            multiline
            maxRows={4}
            placeholder={currentQuestion.content.placeholder}
            value={answer || ""}
            onChange={async ({ target }: ChangeEvent<HTMLInputElement>) => {
              updateAnswer(currentQuestion.id, target.value, 0);
              inputHC(target.value);
            }}
            inputProps={{ maxLength: 400 }}
            sx={{
              width: "100%",
              "& .MuiOutlinedInput-root": {
                backgroundColor: settings.cfg.design
                  ? "rgba(154,154,175, 0.2)"
                  : "#FFFFFF",
              },
              "&:focus-visible": {
                borderColor: theme.palette.primary.main,
              },
            }}
          />
        }
      </Box>
      {!isHorizontal &&
        currentQuestion.content.back &&
        currentQuestion.content.back !== " " && (
          <Box sx={{ margin: "15px", width: "40vw" }}>
            <img
              key={currentQuestion.id}
              src={currentQuestion.content.back}
              style={{ width: "100%", height: "100%", objectFit: "cover" }}
              alt=""
            />
          </Box>
        )}
    </Box>
  );
};
