import { create } from "zustand";
import { devtools } from "zustand/middleware";

import type { QuestionVariant } from "@frontend/squzanswerer";

type Answer = {
  questionId: string;
  answer: string | string[];
};

type OwnVariant = {
  contentId: string;
  variant: QuestionVariant;
};

interface QuizViewStore {
  answers: Answer[];
  ownVariants: OwnVariant[];
}

export const useQuizViewStore = create<QuizViewStore>()(
  devtools(
    (set, get) => ({
      answers: [],
      ownVariants: [],
    }),
    {
      name: "quizView",
    }
  )
);

export const updateAnswer = (questionId: string, answer: string | string[]) => {
  const answers = [...useQuizViewStore.getState().answers];
  const answerIndex = answers.findIndex((answer) => questionId === answer.questionId);

  if (answerIndex < 0) {
    answers.push({ questionId, answer });
  } else {
    answers[answerIndex] = { questionId, answer };
  }

  useQuizViewStore.setState({ answers });
};

export const deleteAnswer = (questionId: string) => {
  const answers = [...useQuizViewStore.getState().answers];
  const filteredItems = answers.filter((answer) => questionId !== answer.questionId);

  useQuizViewStore.setState({ answers: filteredItems });
};

export const updateOwnVariant = (contentId: string, answer: string) => {
  const ownVariants = [...useQuizViewStore.getState().ownVariants];
  const ownVariantIndex = ownVariants.findIndex((variant) => variant.contentId === contentId);

  if (ownVariantIndex < 0) {
    ownVariants.push({
      contentId,
      variant: {
        id: getRandom(),
        answer,
        extendedText: "",
        hints: "",
        originalImageUrl: "",
      },
    });
  } else {
    ownVariants[ownVariantIndex].variant.answer = answer;
  }

  useQuizViewStore.setState({ ownVariants });
};

export const deleteOwnVariant = (contentId: string) => {
  const ownVariants = [...useQuizViewStore.getState().ownVariants];

  const filteredOwnVariants = ownVariants.filter((variant) => variant.contentId !== contentId);

  useQuizViewStore.setState({ ownVariants: filteredOwnVariants });
};

function getRandom() {
  const min = Math.ceil(1000000);
  const max = Math.floor(10000000);

  return String(Math.floor(Math.random() * (max - min)) + min);
}
