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

type Variants = {
  answer: string;
  answerLong: string;
  hints: string;
};

interface Question {
  id: number;
  title: string;
  description: string;
  type: string;
  required: true;
  deleted: true;
  page: number;
  content: {
    variants: Variants[];
    own: boolean;
    multi: boolean;
  };
  version: number;
  parent_ids: number[];
  created_at: string;
  updated_at: string;
}

interface QuestionStore {
  listQuestions: any;
  openedModalSettings: string;
}

export const questionStore = create<QuestionStore>()(
  persist(
    () => ({
      listQuestions: [],
      openedModalSettings: "",
    }),

    {
      name: "question",
    }
  )
);
export const updateQuestionsList = (index: number, data: any) => {
  const array = [...questionStore.getState()["listQuestions"]];
  array.splice(index, 1, { ...array[index], ...data });
  questionStore.setState({ listQuestions: array });
};

export const updateQuestionsLists = (updatedQuestions: any[]) => {
  questionStore.setState({ listQuestions: updatedQuestions });
};

export const createQuestion = (id: number) => {
  const idQ = getRandom(1000000, 10000000);
  const newData = [...questionStore.getState()["listQuestions"]]; //пересоздание массива
  newData.push({
    id: idQ,
    title: "",
    description: "",
    type: "",
    required: true,
    deleted: true,
    page: 0,
    content: {
      variants: [
        {
          answer: "",
          answerLong: "",
          hints: "",
        },
      ],
      own: true,
      multi: true,
    },
    version: 0,
    parent_ids: [0],
    created_at: "",
    updated_at: "",
  });
  questionStore.setState({ listQuestions: newData });
};

export const removeQuestion = (index: number) => {
  const array = [...questionStore.getState()["listQuestions"]];
  array.splice(index, 1);
  questionStore.setState({ listQuestions: array });
};

export const resetSomeField = (data: any) => {
  questionStore.setState(data);
};

export const findQuestionById = (id_question: number): null | any => {
  let found = null;
  questionStore.getState()["listQuestions"].some((quiz: any, index: number) => {
    if (quiz.id_question === id_question) {
      found = { quiz, index };
      return true;
    }
  });
  return found;
};

function getRandom(min: number, max: number) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}
