import { QuestionVariant } from "@model/questionTypes/shared";
import { produce } from "immer";
import { nanoid } from "nanoid";
import { create } from "zustand";
import { devtools } from "zustand/middleware";
import type { Moment } from "moment";
import { QuizStep } from "@model/settingsData";

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

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

interface QuizViewStore {
    answers: QuestionAnswer[];
    ownVariants: OwnVariant[];
    pointsSum: number;
    points: Record<string, number>;
    currentQuizStep: QuizStep;
}

export const useQuizViewStore = create<QuizViewStore>()(
    devtools(
        (set, get) => ({
            answers: [],
            ownVariants: [],
            points: {},
            pointsSum: 0,
            currentQuizStep: "startpage",
        }),
        {
            name: "quizView",
            enabled: import.meta.env.DEV,
            trace: import.meta.env.DEV,
        }
    )
);

function setProducedState<A extends string | { type: string; }>(
    recipe: (state: QuizViewStore) => void,
    action?: A,
) {
    useQuizViewStore.setState(state => produce(state, recipe), false, action);
}

const calcPoints = () => {
    const storePoints = useQuizViewStore.getState().points;
    let sum = Object.values(storePoints).reduce((accumulator, currentValue) => accumulator + currentValue)
    console.log("сумма ", sum)
    useQuizViewStore.setState({ pointsSum: sum })
}

export const updateAnswer = (
    questionId: string,
    answer: string | string[] | Moment,
    points: number
) => {
    setProducedState(state => {
        const index = state.answers.findIndex(answer => questionId === answer.questionId);

        if (index < 0) {
            state.answers.push({ questionId, answer });
        } else {
            state.answers[index] = { questionId, answer };
        }
    }, {
        type: "updateAnswer",
        questionId,
        answer
    })
    const storePoints = useQuizViewStore.getState().points;
    useQuizViewStore.setState({ points: { ...storePoints, ...{ [questionId]: points } } })
    calcPoints()
};

export const deleteAnswer = (questionId: string) => useQuizViewStore.setState(state => ({
    answers: state.answers.filter(answer => questionId !== answer.questionId)
}), false, {
    type: "deleteAnswer",
    questionId
});

export const updateOwnVariant = (id: string, answer: string) => setProducedState(state => {
    const index = state.ownVariants.findIndex((variant) => variant.id === id);

    if (index < 0) {
        state.ownVariants.push({
            id,
            variant: {
                id: nanoid(),
                answer,
                extendedText: "",
                hints: "",
                originalImageUrl: "",
            },
        });
    } else {
        state.ownVariants[index].variant.answer = answer;
    }
}, {
    type: "updateOwnVariant",
    id,
    answer
});

export const deleteOwnVariant = (id: string) => useQuizViewStore.setState(state => ({
    ownVariants: state.ownVariants.filter((variant) => variant.id !== id)
}), false, {
    type: "deleteOwnVariant",
    id
});

export const setCurrentQuizStep = (currentQuizStep: QuizStep) => useQuizViewStore.setState({
    currentQuizStep
}, false, {
    type: "setCurrentQuizStep",
    currentQuizStep
});
