import { create } from "zustand";
import { editor } from "monaco-editor";
import { CodeEditorState } from "@/types";
import { DEFAULT_THEME } from "@/constants/editor/themes";
import { DEFAULT_VALUE } from "@/constants/editor/values";
import { DEFAULT_FONT_SIZE } from "@/constants/editor/options";
import { DEFAULT_LANGUAGE } from "@/constants/editor/languages";
import { persist, createJSONStorage } from "zustand/middleware";

const getSavedCode = (language: string) =>
  localStorage.getItem(`code-editor-${language}`) ||
  DEFAULT_VALUE.find((v) => v.key === language)?.value ||
  "";

const saveCode = (language: string, code: string) =>
  localStorage.setItem(`code-editor-${language}`, code);

export const useCodeEditorStore = create<CodeEditorState>()(
  persist(
    (set, get) => ({
      language: DEFAULT_LANGUAGE,
      theme: DEFAULT_THEME,
      fontSize: DEFAULT_FONT_SIZE,
      editor: null,

      setLanguage: (language: string) => {
        const { editor: currentEditor, language: currentLanguage } = get();
        const currentCode = currentEditor?.getValue() || "";
        if (currentEditor) saveCode(currentLanguage, currentCode);
        const savedCode = getSavedCode(language);
        if (savedCode && currentEditor) currentEditor.setValue(savedCode);
        set({ language });
      },
      setTheme: (theme: string) => set({ theme }),
      setFontSize: (fontSize: number) => set({ fontSize }),
      setEditor: (editor: editor.IStandaloneCodeEditor) => {
        const savedCode = getSavedCode(get().language);
        if (savedCode) editor.setValue(savedCode);
        set({ editor });
      },
    }),
    {
      name: "code-editor-storage",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        language: state.language,
        theme: state.theme,
        fontSize: state.fontSize,
      }),
    }
  )
);
