"use client"

import { create } from "zustand"
import { persist } from "zustand/middleware"
import { debouncedPersistJSONStorage } from "@/lib/stores/debounced-json-storage"
import { normalizeMailBackgroundId } from "@/lib/mail-settings/constants"
import type {
  InboxSortMode,
  MailBackgroundId,
  MailDensity,
  MailThemeMode,
  ReadingPaneMode,
} from "@/lib/mail-settings/types"

type MailSettingsState = {
  quickSettingsOpen: boolean
  themeDialogOpen: boolean
  density: MailDensity
  themeMode: MailThemeMode
  backgroundId: MailBackgroundId
  inboxSort: InboxSortMode
  readingPane: ReadingPaneMode
  conversationMode: boolean
}

type MailSettingsActions = {
  setQuickSettingsOpen: (open: boolean) => void
  setThemeDialogOpen: (open: boolean) => void
  setDensity: (density: MailDensity) => void
  setThemeMode: (mode: MailThemeMode) => void
  setBackgroundId: (id: MailBackgroundId) => void
  setInboxSort: (sort: InboxSortMode) => void
  setReadingPane: (mode: ReadingPaneMode) => void
  setConversationMode: (enabled: boolean) => void
}

const defaults: MailSettingsState = {
  quickSettingsOpen: false,
  themeDialogOpen: false,
  density: "default",
  themeMode: "system",
  backgroundId: "none",
  inboxSort: "default",
  readingPane: "none",
  conversationMode: true,
}

export const useMailSettingsStore = create<
  MailSettingsState & MailSettingsActions
>()(
  persist(
    (set) => ({
      ...defaults,

      setQuickSettingsOpen: (open) => set({ quickSettingsOpen: open }),
      setThemeDialogOpen: (open) => set({ themeDialogOpen: open }),
      setDensity: (density) => set({ density }),
      setThemeMode: (themeMode) => set({ themeMode }),
      setBackgroundId: (backgroundId) => set({ backgroundId }),
      setInboxSort: (inboxSort) => set({ inboxSort }),
      setReadingPane: (readingPane) => set({ readingPane }),
      setConversationMode: (conversationMode) => set({ conversationMode }),
    }),
    {
      name: "ultimail-mail-settings",
      storage: debouncedPersistJSONStorage,
      partialize: (s) => ({
        density: s.density,
        themeMode: s.themeMode,
        backgroundId: s.backgroundId,
        inboxSort: s.inboxSort,
        readingPane: s.readingPane,
        conversationMode: s.conversationMode,
      }),
      merge: (persisted, current) => {
        const p = persisted as Partial<MailSettingsState> | undefined
        if (!p) return current
        return {
          ...current,
          ...p,
          backgroundId: normalizeMailBackgroundId(
            (p.backgroundId as string) ?? "none"
          ),
        }
      },
    }
  )
)
