import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { InstanceListItem } from '../types'
import * as api from '../api'

export const useInstancesStore = defineStore('instances', () => {
  // 状态
  const instances = ref<InstanceListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const autoRefreshEnabled = ref(true)
  let refreshTimer: number | null = null

  // 计算属性
  const runningCount = computed(() =>
    instances.value.filter(i => i.status === 'Running').length
  )

  const stoppedCount = computed(() =>
    instances.value.filter(i => i.status === 'Stopped').length
  )

  const errorCount = computed(() =>
    instances.value.filter(i => i.status === 'Error').length
  )

  // 方法
  async function loadInstances() {
    loading.value = true
    error.value = null
    try {
      instances.value = await api.getAllInstances()
    } catch (err) {
      error.value = '加载实例列表失败'
      console.error(err)
    } finally {
      loading.value = false
    }
  }

  async function startInstance(id: string) {
    try {
      await api.startInstance(id)
      await loadInstances()
    } catch (err) {
      console.error('启动实例失败:', err)
      throw err
    }
  }

  async function stopInstance(id: string) {
    try {
      await api.stopInstance(id)
      await loadInstances()
    } catch (err) {
      console.error('停止实例失败:', err)
      throw err
    }
  }

  async function deleteInstance(id: string) {
    try {
      await api.deleteInstance(id)
      await loadInstances()
    } catch (err) {
      console.error('删除实例失败:', err)
      throw err
    }
  }

  function startAutoRefresh(interval: number = 2000) {
    stopAutoRefresh()
    if (autoRefreshEnabled.value) {
      refreshTimer = window.setInterval(() => {
        loadInstances()
      }, interval)
    }
  }

  function stopAutoRefresh() {
    if (refreshTimer !== null) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }

  function setAutoRefreshEnabled(enabled: boolean) {
    autoRefreshEnabled.value = enabled
    if (!enabled) {
      stopAutoRefresh()
    }
  }

  // 获取单个实例
  function getInstance(id: string) {
    return instances.value.find(i => i.instanceId === id)
  }

  return {
    // 状态
    instances,
    loading,
    error,
    autoRefreshEnabled,
    // 计算属性
    runningCount,
    stoppedCount,
    errorCount,
    // 方法
    loadInstances,
    startInstance,
    stopInstance,
    deleteInstance,
    startAutoRefresh,
    stopAutoRefresh,
    setAutoRefreshEnabled,
    getInstance
  }
})
