import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { TableStructure } from '@/types'

const MAX_HISTORY = 30

export const useHistoryStore = defineStore('history', () => {
  const undoStack = ref<TableStructure[]>([])
  const redoStack = ref<TableStructure[]>([])

  const canUndo = computed(() => undoStack.value.length > 0)
  const canRedo = computed(() => redoStack.value.length > 0)
  const undoCount = computed(() => undoStack.value.length)
  const redoCount = computed(() => redoStack.value.length)

  function pushState(state: TableStructure) {
    undoStack.value.push(state)
    
    // 限制历史记录数量
    if (undoStack.value.length > MAX_HISTORY) {
      undoStack.value.shift()
    }
    
    // 清空重做栈
    redoStack.value = []
  }

  function undo(): TableStructure | null {
    if (undoStack.value.length === 0) return null
    
    const state = undoStack.value.pop()!
    return state
  }

  function saveCurrentForRedo(current: TableStructure) {
    redoStack.value.push(current)
    
    if (redoStack.value.length > MAX_HISTORY) {
      redoStack.value.shift()
    }
  }

  function redo(): TableStructure | null {
    if (redoStack.value.length === 0) return null
    
    const state = redoStack.value.pop()!
    return state
  }

  function saveCurrentForUndo(current: TableStructure) {
    undoStack.value.push(current)
    
    if (undoStack.value.length > MAX_HISTORY) {
      undoStack.value.shift()
    }
  }

  function clear() {
    undoStack.value = []
    redoStack.value = []
  }

  return {
    undoStack,
    redoStack,
    canUndo,
    canRedo,
    undoCount,
    redoCount,
    pushState,
    undo,
    redo,
    saveCurrentForRedo,
    saveCurrentForUndo,
    clear
  }
})
