import { create } from 'zustand'
import type { CommandTemplate } from '@shared/ipc'
import { isPreview as PREVIEW } from '../isPreview'
import { logError } from '../reportError'
import { createReconciler } from '../lib/reconcile'

// Sample templates so the Settings tab has content during UI design.
const seed: CommandTemplate[] = PREVIEW
  ? [
      { id: 't1', name: 'Write thumbnail, no mtime', args: '--write-thumbnail --no-mtime' },
      { id: 't2', name: 'Verbose log', args: '--verbose' }
    ]
  : []

interface TemplatesState {
  templates: CommandTemplate[]
  /** add a new template or update an existing one (matched by id) */
  save: (template: CommandTemplate) => void
  remove: (id: string) => void
  /** re-fetch persisted templates from main (a backup restore replaces them underneath) */
  reload: () => void
}

// Mutations apply main's authoritative return (sanitized names/args, capped list)
// via a latest-wins reconciler so the optimistic list matches disk (L142).
const reconcile = createReconciler()

export const useTemplates = create<TemplatesState>((set) => ({
  templates: seed,

  save: (template) => {
    set((s) => ({ templates: [template, ...s.templates.filter((t) => t.id !== template.id)] }))
    if (!PREVIEW)
      reconcile(
        'templates',
        window.api.saveTemplate(template),
        (templates) => set({ templates }),
        logError('saveTemplate')
      )
  },

  remove: (id) => {
    set((s) => ({ templates: s.templates.filter((t) => t.id !== id) }))
    if (!PREVIEW)
      reconcile(
        'templates',
        window.api.removeTemplate(id),
        (templates) => set({ templates }),
        logError('removeTemplate')
      )
  },

  reload: () => {
    if (PREVIEW) return
    window.api
      .listTemplates()
      .then((templates) => set({ templates }))
      .catch(logError('listTemplates'))
  }
}))

// Load persisted templates on startup.
if (!PREVIEW) useTemplates.getState().reload()
