import { createPinia, type PiniaPluginContext } from 'pinia'

// 定义插件选项接口
interface PersistenceOptions {
  key?: string
  storage?: Storage
  paths?: string[]
}

// 数据持久化插件
function createPersistedStatePlugin(options: PersistenceOptions = {}) {
  return function (context: PiniaPluginContext) {
    const { store, options: storeOptions } = context

    // 检查 store 是否启用持久化
    const { persist } = storeOptions as { persist?: boolean | PersistenceOptions }
    if (!persist) return

    const {
      key = `pinia-${store.$id}`,
      storage = localStorage,
      paths = [],
    } = { ...options, ...(typeof persist === 'object' ? persist : {}) }

    // 恢复状态
    try {
      const stored = storage.getItem(key)
      if (stored) {
        const data = JSON.parse(stored)

        // 如果指定了 paths，只恢复指定的字段
        if (paths.length > 0) {
          paths.forEach((path: string) => {
            if (data[path] !== undefined) {
              store.$patch({ [path]: data[path] })
            }
          })
        } else {
          store.$patch(data)
        }
      }
    } catch (error) {
      console.warn(`Failed to restore state for store "${store.$id}":`, error)
    }

    // 监听状态变化并保存
    store.$subscribe(
      (mutation, state) => {
        try {
          let dataToSave = state

          // 如果指定了 paths，只保存指定的字段
          if (paths.length > 0) {
            dataToSave = paths.reduce(
              (acc: Record<string, unknown>, path: string) => {
                if (state[path] !== undefined) {
                  acc[path] = state[path]
                }
                return acc
              },
              {} as Record<string, unknown>
            )
          }

          storage.setItem(key, JSON.stringify(dataToSave))
        } catch (error) {
          console.warn(`Failed to persist state for store "${store.$id}":`, error)
        }
      },
      { detached: true }
    )
  }
}

// 开发环境调试插件
function createDevToolsPlugin() {
  return function (context: PiniaPluginContext) {
    const { store } = context

    if (import.meta.env.DEV) {
      // 添加调试信息
      store.$onAction(({ name, args, after, onError }) => {
        const startTime = Date.now()
        console.log(`🚀 Action "${name}" started on store "${store.$id}" with args:`, args)

        after(result => {
          const duration = Date.now() - startTime
          console.log(`✅ Action "${name}" finished in ${duration}ms with result:`, result)
        })

        onError(error => {
          const duration = Date.now() - startTime
          console.error(`❌ Action "${name}" failed after ${duration}ms:`, error)
        })
      })

      // 添加状态变化日志
      store.$subscribe((mutation, state) => {
        console.log(`📊 Store "${store.$id}" state changed:`, {
          type: mutation.type,
          storeId: mutation.storeId,
          // payload: mutation.payload, // Removed because 'payload' does not exist on mutation
          newState: state,
        })
      })
    }
  }
}

// 性能监控插件
function createPerformancePlugin() {
  return function (context: PiniaPluginContext) {
    const { store } = context

    // 添加性能统计
    const stats = {
      actionCount: 0,
      mutationCount: 0,
      lastActionTime: 0,
      averageActionTime: 0,
    }

    store.$onAction(({ name, after, onError }) => {
      const startTime = performance.now()
      stats.actionCount++

      after(() => {
        const duration = performance.now() - startTime
        stats.lastActionTime = duration
        stats.averageActionTime = (stats.averageActionTime + duration) / 2

        if (import.meta.env.DEV && duration > 100) {
          console.warn(
            `⚠️ Slow action "${name}" in store "${store.$id}" took ${duration.toFixed(2)}ms`
          )
        }
      })

      onError(() => {
        if (import.meta.env.DEV) {
          console.error(`💥 Action "${name}" in store "${store.$id}" threw an error`)
        }
      })
    })

    store.$subscribe(() => {
      stats.mutationCount++
    })

    // 将统计信息添加到 store 实例
    ;(store as { $stats?: typeof stats }).$stats = stats
  }
}

/**
 * Pinia Store 配置 - 使用 Pinia 3.0.3 最佳实践
 * 包含数据持久化、开发工具、性能监控等插件
 */
function createAppPinia() {
  const pinia = createPinia()

  // 注册数据持久化插件
  pinia.use(
    createPersistedStatePlugin({
      storage: localStorage, // 默认使用 localStorage
    })
  )

  // 注册开发环境调试插件
  if (import.meta.env.DEV) {
    pinia.use(createDevToolsPlugin())
    pinia.use(createPerformancePlugin())
  }

  return pinia
}

// 扩展 Pinia 类型定义
declare module 'pinia' {
  export interface DefineStoreOptionsBase<S, Store> {
    // 添加持久化选项
    persist?:
      | boolean
      | {
          key?: string
          storage?: Storage
          paths?: string[]
        }
  }

  export interface PiniaCustomProperties {
    // 添加自定义属性
    $stats?: {
      actionCount: number
      mutationCount: number
      lastActionTime: number
      averageActionTime: number
    }
  }
}

/**
 * Pinia Stores 统一导出
 */
export { useCounterStore } from './counter'
export { useUserStore } from './user'

// 创建并导出 Pinia 实例（按照 Pinia 3.x 最佳实践）
export const pinia = createAppPinia()

// 如果需要在应用启动时初始化某些store，可以在这里添加
export function initializeStores() {
  // 可以在这里执行一些初始化逻辑
  // 例如：从localStorage恢复状态、设置默认值等

  if (import.meta.env.DEV) {
    console.log('🏪 Pinia stores initialized')
  }
}

export default pinia

// 导出插件工厂函数，供其他项目使用
export { createPersistedStatePlugin, createDevToolsPlugin, createPerformancePlugin }
