import { defineStore } from 'pinia'
import { ref, computed, onMounted } from 'vue'
import api from '@/services/api'
import { useGarageStore } from './garageStore'

export const useAppModeStore = defineStore('appMode', () => {
  // State
  const mode = ref('personal') // backend compatible values: 'personal' or 'fleet'
  const isLoading = ref(false)

  // Getters
  const isPrivateGarage = computed(() => mode.value === 'personal')
  const isCorporateFleet = computed(() => mode.value === 'fleet')

  // Actions
  async function setMode(newMode) {
    // Map UI values to backend compatible values
    let backendMode = newMode
    if (newMode === 'private_garage') {
      backendMode = 'personal'
    } else if (newMode === 'corporate_fleet') {
      backendMode = 'fleet'
    }
    
    if (!['personal', 'fleet'].includes(backendMode)) {
      console.error('Invalid mode:', newMode)
      return
    }
    mode.value = backendMode
    persistMode(backendMode)
    await saveModeToBackend(backendMode)
  }

  function toggleMode() {
    const newMode = mode.value === 'personal' ? 'fleet' : 'personal'
    setMode(newMode)
  }

  // SSR-safe localStorage persistence
  function persistMode(mode) {
    if (typeof window !== 'undefined') {
      localStorage.setItem('ui_mode', mode)
    }
  }

  function getInitialMode() {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('ui_mode')
      // Map UI values to backend compatible values
      if (saved === 'private_garage' || saved === 'personal') {
        return 'personal'
      } else if (saved === 'corporate_fleet' || saved === 'fleet') {
        return 'fleet'
      }
    }
    // Default mode
    return 'personal'
  }

  // Load user preferences from backend on app startup
  async function loadModeFromBackend() {
    if (typeof window === 'undefined') return
    try {
      isLoading.value = true
      const response = await api.get('/users/me')
      const user = response.data
      if (user.ui_mode && ['personal', 'fleet'].includes(user.ui_mode)) {
        mode.value = user.ui_mode
        persistMode(user.ui_mode)
      }
    } catch (error) {
      console.warn('Failed to load UI mode from backend, using local storage', error)
    } finally {
      isLoading.value = false
    }
  }

  // Save mode to backend via PATCH /users/me/preferences
  async function saveModeToBackend(newMode) {
    try {
      await api.patch('/users/me/preferences', {
        ui_mode: newMode
      })
      
      // Also update active organization based on mode
      // When switching to fleet mode, we need to set an active organization
      // When switching to personal mode, we should clear the active organization
      if (newMode === 'fleet') {
        // Try to get the user's active organization from auth store
        // For now, we'll just make sure the backend knows we're in fleet mode
        // The actual organization selection should happen elsewhere
        console.log('Switched to fleet mode - organization selection may be needed')
      } else if (newMode === 'personal') {
        // Clear active organization when switching to personal mode
        try {
          await api.patch('/users/me/active-organization', {
            organization_id: null
          })
          console.log('Cleared active organization for personal mode')
        } catch (orgError) {
          console.warn('Failed to clear active organization', orgError)
          // Non-critical error, continue
        }
      }

      // Refresh the garage store to reflect the new scope
      try {
        const garageStore = useGarageStore()
        await garageStore.fetchVehicles()
        console.log('Garage store refreshed after mode change')
      } catch (refreshError) {
        console.warn('Failed to refresh garage store', refreshError)
        // Non-critical error, continue
      }
    } catch (error) {
      console.error('Failed to save UI mode to backend', error)
      // Optionally revert local state? For now just log.
    }
  }

  // Initialize
  mode.value = getInitialMode()
  // Load from backend after store creation (call in component's onMounted)
  // We expose loadModeFromBackend for components to call

  return {
    mode,
    isLoading,
    isPrivateGarage,
    isCorporateFleet,
    setMode,
    toggleMode,
    loadModeFromBackend,
  }
})