import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type ExportFormat = 'markdown' | 'text' | 'html' | 'psa'
type TreeLibraryView = 'grid' | 'list' | 'table'
type TreeSortBy = 'usage_count' | 'updated_at' | 'created_at' | 'name' | 'name_desc' | 'version'
type EditorMode = 'form' | 'code'

interface UserPreferencesState {
  defaultExportFormat: ExportFormat
  setDefaultExportFormat: (format: ExportFormat) => void
  treeLibraryView: TreeLibraryView
  setTreeLibraryView: (view: TreeLibraryView) => void
  treeLibrarySortBy: TreeSortBy
  setTreeLibrarySortBy: (sortBy: TreeSortBy) => void
  preferredEditorMode: EditorMode
  setPreferredEditorMode: (mode: EditorMode) => void
  sidebarCollapsed: boolean
  toggleSidebar: () => void
  dashboardMyFlowsView: TreeLibraryView
  setDashboardMyFlowsView: (view: TreeLibraryView) => void
}

export const useUserPreferencesStore = create<UserPreferencesState>()(
  persist(
    (set, get) => ({
      defaultExportFormat: 'markdown',
      setDefaultExportFormat: (format) => set({ defaultExportFormat: format }),
      treeLibraryView: 'grid',
      setTreeLibraryView: (view) => set({ treeLibraryView: view }),
      treeLibrarySortBy: 'usage_count',
      setTreeLibrarySortBy: (sortBy) => set({ treeLibrarySortBy: sortBy }),
      preferredEditorMode: 'form',
      setPreferredEditorMode: (mode) => set({ preferredEditorMode: mode }),
      sidebarCollapsed: false,
      toggleSidebar: () => set({ sidebarCollapsed: !get().sidebarCollapsed }),
      dashboardMyFlowsView: 'grid',
      setDashboardMyFlowsView: (view) => set({ dashboardMyFlowsView: view }),
    }),
    {
      name: 'user-preferences-storage',
    }
  )
)

export default useUserPreferencesStore
