import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { api } from '../services/api'
import type { SystemInfo, SystemStatus } from '../types'

interface SystemState {
  // System information
  systemInfo: SystemInfo | null
  systemStatus: SystemStatus | null
  isInitialized: boolean
  isConnected: boolean
  
  // Loading states
  isLoading: boolean
  error: string | null
  
  // Actions
  initializeSystem: () => Promise<void>
  updateSystemStatus: (status: SystemStatus) => void
  updateConnectionStatus: (connected: boolean) => void
  clearError: () => void
  setError: (error: string) => void
}

export const useSystemStore = create<SystemState>()(
  persist(
    (set, get) => ({
      // Initial state
      systemInfo: null,
      systemStatus: null,
      isInitialized: false,
      isConnected: false,
      isLoading: false,
      error: null,

      // Initialize system - called on app startup
      initializeSystem: async () => {
        const { isInitialized } = get()
        if (isInitialized) return

        set({ isLoading: true, error: null })

        try {
          // Fetch system information
          const systemInfo = await api.getSystemInfo()
          
          // Fetch initial system status
          const systemStatus = await api.getSystemStatus()

          set({
            systemInfo,
            systemStatus,
            isInitialized: true,
            isLoading: false,
            error: null,
          })
        } catch (error) {
          console.error('Failed to initialize system:', error)
          set({
            isLoading: false,
            error: error instanceof Error ? error.message : 'Failed to initialize system',
          })
        }
      },

      // Update system status (called from WebSocket)
      updateSystemStatus: (status: SystemStatus) => {
        set({ systemStatus: status })
      },

      // Update connection status
      updateConnectionStatus: (connected: boolean) => {
        set({ isConnected: connected })
      },

      // Clear error
      clearError: () => {
        set({ error: null })
      },

      // Set error
      setError: (error: string) => {
        set({ error })
      },
    }),
    {
      name: 'system-store',
      partialize: (state) => ({
        systemInfo: state.systemInfo,
        // Don't persist connection status or loading states
      }),
    }
  )
)
