import { sendAnswer } from "@/api/quizRelase";
import { RealTypedQuizQuestion } from "@/model/questionTypes/shared";
import { OwnVariant, QuestionAnswer, createQuizViewStore } from "@/stores/quizView";
import moment from "moment";
import { notReachable } from "./notReachable";

export async function sendQuestionAnswer(
  quizId: string,
  question: RealTypedQuizQuestion,
  questionAnswer: QuestionAnswer | undefined,
  ownVariants: OwnVariant[]
) {
  if (!questionAnswer) {
    return sendAnswer({
      questionId: question.id,
      body: "",
      qid: quizId,
    });
  }
  switch (question.type) {
    case "date": {
      let answer = "";

      if (question.content.isRange) {
        if (!Array.isArray(questionAnswer.answer)) throw new Error("Cannot send answer in range question");

        let from = Number(questionAnswer.answer[0]);
        let to = Number(questionAnswer.answer[1]);

        if (
          from !== 0 &&
          to !== 0 &&
          from !== Math.min(Number(questionAnswer.answer[0]), Number(questionAnswer.answer[1]))
        ) {
          from = Math.min(Number(questionAnswer.answer[0]), Number(questionAnswer.answer[1]));
          to = Math.max(Number(questionAnswer.answer[0]), Number(questionAnswer.answer[1]));
        }

        answer = `${!from ? "_" : moment(from).format("YYYY.MM.DD")} - ${!to ? "_" : moment(to).format("YYYY.MM.DD")}`;
      } else {
        if (!moment.isMoment(questionAnswer.answer)) throw new Error("Cannot send answer in date question");

        answer = moment(questionAnswer.answer).format("YYYY.MM.DD");
      }
      return sendAnswer({
        questionId: question.id,
        body: answer,
        qid: quizId,
      });
    }
    case "emoji": {
      if (question.content.multi) {
        const answer = questionAnswer.answer as string[];
        let answerString = ``;

        const selectedVariants = question.content.variants.filter((v) => answer.includes(v.id));

        selectedVariants.forEach((variant) => {
          const ownVariantData = ownVariants.find((v) => v.id === variant.id)?.variant;
          const customEmoji = ownVariantData?.extendedText || "";
          const emojiToSend = customEmoji || variant.extendedText;
          const textToSend = variant.isOwn ? ownVariantData?.answer || "" : variant.answer;
          answerString += `\`${emojiToSend} ${textToSend}\`,`;
        });

        answerString = answerString.slice(0, -1);

        return sendAnswer({
          questionId: question.id,
          body: answerString,
          qid: quizId,
        });
      }

      // Fallback for old string format for single choice
      const answer = questionAnswer.answer as string;
      const variant = question.content.variants.find((v) => v.id === answer);
      if (!variant) {
        // This can happen if the answer is not set, so we don't throw an error, just send empty
        return sendAnswer({
          questionId: question.id,
          body: "",
          qid: quizId,
        });
      }

      const ownVariantData = ownVariants.find((v) => v.id === variant.id)?.variant;
      const customEmoji = ownVariantData?.extendedText || "";
      const emojiToSend = customEmoji || variant.extendedText;
      const textToSend = variant.isOwn ? ownVariantData?.answer || "" : variant.answer;
      const body = `${emojiToSend} ${textToSend}`.trim();

      return sendAnswer({
        questionId: question.id,
        body: body,
        qid: quizId,
      });
    }
    case "file": {
      return;
    }
    case "images": {
      if (question.content.multi) {
        const answer = questionAnswer.answer;
        const ownAnswer = Array.isArray(answer)
          ? ownVariants[ownVariants.findIndex((variant) => answer.some((a: string) => a === variant.id))]?.variant
              ?.answer || ""
          : ownVariants[ownVariants.findIndex((variant) => variant.id === questionAnswer.answer)]?.variant?.answer ||
            "";

        if (moment.isMoment(answer)) throw new Error("Answer is Moment in Variant question");

        //Оставляем только выбранные варианты
        const selectedVariants = question.content.variants.filter((v) => answer.includes(v.id));

        let answerString = ``;
        selectedVariants.forEach((e) => {
          if (!e.isOwn || (e.isOwn && question.content.own)) {
            let imageValue = e.extendedText;
            if (e.isOwn) {
              // Берем fileId из ownVariants для own вариантов
              const ownVariantData = ownVariants.find((v) => v.id === e.id)?.variant;
              if (ownVariantData?.originalImageUrl) {
                // Конструируем полный URL для own вариантов
                const baseUrl =
                  "https://s3.timeweb.cloud/3c580be9-cf31f296-d055-49cf-b39e-30c7959dc17b/squizimages/55c25eb9-4533-4d51-9da5-54e63e8aeace/";
                // Убираем расширение файла из fileId
                const fileIdWithoutExtension = ownVariantData.originalImageUrl.replace(
                  /\.(jpg|jpeg|png|gif|webp)$/i,
                  ""
                );
                imageValue = baseUrl + fileIdWithoutExtension;
              }
            }

            const body = {
              Image: imageValue,
              Description: e.isOwn ? ownAnswer : e.answer,
            };
            answerString += `\`${JSON.stringify(body)}\`,`;
          }
        });
        answerString = answerString.slice(0, -1);

        return sendAnswer({
          questionId: question.id,
          body: answerString,
          qid: quizId,
        });
      }

      const variant = question.content.variants.find((v) => v.id === questionAnswer.answer);

      if (!variant) throw new Error(`Cannot find variant with id ${questionAnswer.answer} in question ${question.id}`);

      // Берем fileId из ownVariants для own вариантов
      const ownVariantData = ownVariants.find((v) => v.id === variant.id)?.variant;

      let imageValue = variant.extendedText;
      if (variant.isOwn) {
        if (ownVariantData?.originalImageUrl) {
          // Конструируем полный URL для own вариантов
          const baseUrl =
            "https://s3.timeweb.cloud/3c580be9-cf31f296-d055-49cf-b39e-30c7959dc17b/squizimages/55c25eb9-4533-4d51-9da5-54e63e8aeace/";
          // Убираем расширение файла из fileId
          const fileIdWithoutExtension = ownVariantData.originalImageUrl.replace(/\.(jpg|jpeg|png|gif|webp)$/i, "");
          imageValue = baseUrl + fileIdWithoutExtension;
        }
      }

      const body = {
        Image: imageValue,
        Description: ownVariantData ? ownVariantData.answer : variant.answer,
      };
      if (!body) throw new Error(`Body of answer in question ${question.id} is undefined`);

      return sendAnswer({
        questionId: question.id,
        body: `\`${JSON.stringify(body)}\``,
        qid: quizId,
      });
    }
    case "number": {
      if (typeof questionAnswer.answer !== "string") throw new Error("Cannot send answer in select question");

      return sendAnswer({
        questionId: question.id,
        body: questionAnswer.answer,
        qid: quizId,
      });
    }
    case "page": {
      return;
    }
    case "rating": {
      if (typeof questionAnswer.answer !== "string") throw new Error("Cannot send answer in select question");

      return sendAnswer({
        questionId: question.id,
        body: String(questionAnswer.answer) + " из " + question.content.steps,
        qid: quizId,
      });
    }
    case "select": {
      if (typeof questionAnswer.answer !== "string") throw new Error("Cannot send answer in select question");

      const variant = question.content.variants[Number(questionAnswer.answer)];
      if (!variant) throw new Error(`Cannot find variant with id ${questionAnswer.answer} in question ${question.id}`);

      return sendAnswer({
        questionId: question.id,
        body: variant.answer,
        qid: quizId,
      });
    }
    case "text": {
      if (moment.isMoment(questionAnswer.answer)) throw new Error("Cannot send Moment in text question");

      return sendAnswer({
        questionId: question.id,
        body: questionAnswer.answer,
        qid: quizId,
      });
    }
    case "variant": {
      if (question.content.multi) {
        const answer = questionAnswer.answer;
        if (moment.isMoment(answer)) throw new Error("Answer is Moment in Variant question");

        const ownAnswer = Array.isArray(answer)
          ? ownVariants[ownVariants.findIndex((variant) => answer.some((a: string) => a === variant.id))]?.variant
              ?.answer || ""
          : ownVariants[ownVariants.findIndex((variant) => variant.id === questionAnswer.answer)]?.variant?.answer ||
            "";

        //Оставляем только выбранные варианты
        const selectedVariants = question.content.variants.filter((v) => answer.includes(v.id));

        let answerString = ``;
        selectedVariants.forEach((e) => {
          if (!e.isOwn) answerString += `\`${e.answer}\`,`;
        });

        if (question.content.own && selectedVariants.some((v) => v.isOwn)) {
          answerString += `\`${ownAnswer}\`,`;
        }
        answerString = answerString.slice(0, -1);

        return sendAnswer({
          questionId: question.id,
          body: answerString,
          qid: quizId,
        });
      }

      const variant = question.content.variants.find((v) => v.id === questionAnswer.answer);
      if (!variant) throw new Error(`Cannot find variant with id ${questionAnswer.answer} in question ${question.id}`);

      return sendAnswer({
        questionId: question.id,
        body: variant.answer,
        qid: quizId,
      });
    }
    case "varimg": {
      const variant = question.content.variants.find((v) => v.id === questionAnswer.answer);
      const ownAnswer =
        ownVariants[ownVariants.findIndex((variant) => variant.id === questionAnswer.answer)]?.variant?.answer || "";

      if (!variant) throw new Error(`Cannot find variant with id ${questionAnswer.answer} in question ${question.id}`);

      let imageValue = variant.extendedText;
      if (variant.isOwn) {
        // Берем fileId из ownVariants для own вариантов
        const ownVariantData = ownVariants.find((v) => v.id === variant.id)?.variant;
        if (ownVariantData?.originalImageUrl) {
          // Конструируем полный URL для own вариантов
          const baseUrl =
            "https://s3.timeweb.cloud/3c580be9-cf31f296-d055-49cf-b39e-30c7959dc17b/squizimages/55c25eb9-4533-4d51-9da5-54e63e8aeace/";
          // Убираем расширение файла из fileId
          const fileIdWithoutExtension = ownVariantData.originalImageUrl.replace(/\.(jpg|jpeg|png|gif|webp)$/i, "");
          imageValue = baseUrl + fileIdWithoutExtension;
        }
      }

      const body = {
        Image: imageValue,
        Description: variant.isOwn ? ownAnswer : variant.answer,
      };
      if (!body) throw new Error(`Body of answer in question ${question.id} is undefined`);

      return sendAnswer({
        questionId: question.id,
        body: `\`${JSON.stringify(body)}\``,
        qid: quizId,
      });
    }
    default:
      notReachable(question);
  }
}
