import { create } from "zustand";
import { produce } from "immer";
import { QuizSettings, QuizSettingsConfig } from "@model/settingsData";
import { AnyTypedQuizQuestion } from "..";

export type QuizStore = QuizSettings & {
  quizId: string;
  preview: boolean;
  changeFaviconAndTitle: boolean;
  quizStep: number;
  nextLoading: boolean;
};

export const useQuizStore = create<QuizStore>(() => ({
  settings: {} as QuizSettingsConfig,
  questions: [],
  quizId: "",
  preview: false,
  changeFaviconAndTitle: false,
  cnt: 0,
  recentlyCompleted: false,
  show_badge: false,
  quizStep: 0,
  nextLoading: false,
}));

export const setQuizData = (data: QuizSettings) => {
  const currentState = useQuizStore.getState();

  useQuizStore.setState((state: QuizStore) => {
    const newState = { ...state, ...data };
    return newState;
  });

  const updatedState = useQuizStore.getState();
};

export const addQuestions = (newQuestions: AnyTypedQuizQuestion[]) =>
  useQuizStore.setState(
    produce((state: QuizStore) => {
      state.questions.push(...newQuestions);
    })
  );
export const addquizid = (id: string) =>
  useQuizStore.setState(
    produce((state: QuizStore) => {
      state.quizId = id;
    })
  );

export const quizStepInc = () =>
  useQuizStore.setState(
    produce((state: QuizStore) => {
      //Дополнительная проверка что мы не вышли за пределы массива вопросов
      if (state.quizStep + 1 <= state.questions.length) {
        state.quizStep += 1;
      }
    })
  );
export const quizStepDec = () =>
  useQuizStore.setState(
    produce((state: QuizStore) => {
      //Дополнительная проверка что мы не вышли на менее чем 0 вопрос
      if (state.quizStep > 0) {
        state.quizStep--;
      }
    })
  );

export const changeNextLoading = (status: boolean) =>
  useQuizStore.setState(
    produce((state: QuizStore) => {
      state.nextLoading = status;
    })
  );
