"use client"

import { create } from "zustand"
import { persist } from "zustand/middleware"
import { debouncedPersistJSONStorage } from "@/lib/stores/debounced-json-storage"
import {
  DOCS_KEYBOARD_SHORTCUTS_STORAGE_KEY,
  type DocsKeyboardShortcutsUserConfig,
  type DocsShortcutBinding,
  type DocsShortcutId,
} from "@/lib/drive/docs-keyboard-shortcuts-config"
import {
  formatDocsShortcutId,
  listDocsKeyboardShortcutCatalog,
  matchDocsShortcutEvent,
  resolveDocsShortcutBinding,
  resolveDocsShortcutBindings,
  sanitizeDocsKeyboardShortcutsUserConfig,
} from "@/lib/drive/docs-keyboard-shortcuts-runtime"

type DocsKeyboardShortcutsState = {
  overrides: DocsKeyboardShortcutsUserConfig
}

type DocsKeyboardShortcutsActions = {
  getBinding: (id: DocsShortcutId) => DocsShortcutBinding
  getBindings: (id: DocsShortcutId) => DocsShortcutBinding[]
  formatShortcut: (id: DocsShortcutId) => string
  matchEvent: (
    event: KeyboardEvent,
    filter?: Parameters<typeof matchDocsShortcutEvent>[2]
  ) => DocsShortcutId | null
  setBinding: (id: DocsShortcutId, binding: DocsShortcutBinding) => void
  resetBinding: (id: DocsShortcutId) => void
  resetAll: () => void
  getCatalog: () => ReturnType<typeof listDocsKeyboardShortcutCatalog>
}

export const useDocsKeyboardShortcutsStore = create<
  DocsKeyboardShortcutsState & DocsKeyboardShortcutsActions
>()(
  persist(
    (set, get) => ({
      overrides: {},

      getBinding: (id) => resolveDocsShortcutBinding(id, get().overrides),

      getBindings: (id) => resolveDocsShortcutBindings(id, get().overrides),

      formatShortcut: (id) => formatDocsShortcutId(id, get().overrides),

      matchEvent: (event, filter) => matchDocsShortcutEvent(event, get().overrides, filter),

      setBinding: (id, binding) => {
        set((state) => ({
          overrides: { ...state.overrides, [id]: binding },
        }))
      },

      resetBinding: (id) => {
        set((state) => {
          const next = { ...state.overrides }
          delete next[id]
          return { overrides: next }
        })
      },

      resetAll: () => set({ overrides: {} }),

      getCatalog: () => listDocsKeyboardShortcutCatalog(get().overrides),
    }),
    {
      name: DOCS_KEYBOARD_SHORTCUTS_STORAGE_KEY,
      storage: debouncedPersistJSONStorage,
      partialize: (state) => ({ overrides: state.overrides }),
      merge: (persisted, current) => ({
        ...current,
        overrides: sanitizeDocsKeyboardShortcutsUserConfig(
          (persisted as DocsKeyboardShortcutsState | undefined)?.overrides
        ),
      }),
    }
  )
)
