// src/stores/useUi.js
import { defineStore } from 'pinia'

const APPEARANCE_STORAGE_KEY = 'appearanceSettings'

const appearanceSettingKeys = [
  'primaryColor',
  'secondaryColor',
  'warningColor',
  'fontFamily',
  'fontSize',
  'animationsEnabled',
  'backgroundColor',
  'theme',
  'accentColorEmpleados',
  'accentColorTareas',
  'accentColorPlanillas',
  'accentColorAsistencias',
  'accentColorConfiguracion',
  'accentColorChat',
  // Per-module table background colors
  'tableBgColorEmpleados',
  'tableBgColorTareas',
  'tableBgColorPlanillas',
  'tableBgColorAsistencias',
  'tableBgColorConfiguracion',
  'desktopNavbarPersistent',
  // Default module views
  'defaultViewEmpleados',
  'defaultViewTareas',
  'defaultViewPlanillas',
  'defaultViewAsistencias',
  'defaultViewConfiguracion',
  'transitionSpeed',
  'chatAgentMessageColor',
  'chatOwnMessageColor',
  'chatInputBoxColor',
  'chatAccentColor',
  'chatBackgroundColor',
  'chatFontColor',
  'chatFontFamily',
  'chatFontSize',

]

const loadSettingsFromLocalStorage = () => {
  try {
    // Check if localStorage is available
    if (typeof localStorage === 'undefined') {
      console.warn('localStorage is not available. Skipping load of appearance settings.');
      return null;
    }
    const savedSettings = localStorage.getItem(APPEARANCE_STORAGE_KEY)
    if (savedSettings) {
      return JSON.parse(savedSettings)
    }
  } catch (error) {
    console.error('Error loading appearance settings from local storage:', error)
  }
  return null
}

const saveSettingsToLocalStorage = (settings) => {
  try {
    // Check if localStorage is available
    if (typeof localStorage === 'undefined') {
      console.warn('localStorage is not available. Skipping save of appearance settings.');
      return;
    }
    localStorage.setItem(APPEARANCE_STORAGE_KEY, JSON.stringify(settings))
  } catch (error) {
    console.error('Error saving appearance settings to local storage:', error)
  }
}

const _saveAppearanceState = (state) => {
  const settingsToSave = {}
  for (const key of appearanceSettingKeys) {
    // Ensure the property exists in the state before trying to save it
    if (state.hasOwnProperty(key)) {
      settingsToSave[key] = state[key]
    }
  }
  saveSettingsToLocalStorage(settingsToSave)
}

export const useUi = defineStore('ui', {
  state: () => {
    const defaultState = {
      sidebarOpen: true, // This is not an appearance setting, kept as default
      primaryColor: '#1976D2',
      secondaryColor: '#424242',
      warningColor: '#FFC107',
      fontFamily: 'Roboto, sans-serif',
      fontSize: 16,
      animationsEnabled: true,
      backgroundColor: '#FFFFFF',
      theme: 'light', // 'light' or 'dark'
      // Module-specific accent colors
      accentColorEmpleados: '#2196F3', // Blue
      accentColorTareas: '#4CAF50',     // Green
      accentColorPlanillas: '#FF9800',  // Orange
      accentColorAsistencias: '#E91E63', // Pink
      accentColorConfiguracion: '#607D8B', // Blue Grey
      accentColorChat: '#0D9488', // Teal - chosen as a default for chat
      // Per-module table background colors - default to white
      tableBgColorEmpleados: '#FFFFFF',
      tableBgColorTareas: '#FFFFFF',
      tableBgColorPlanillas: '#FFFFFF',
      tableBgColorAsistencias: '#FFFFFF',
      tableBgColorConfiguracion: '#FFFFFF',
      backgroundColorChat: '#F0F0F0', // A light gray for chat background by default
      desktopNavbarPersistent: false,
      // Default module views
      'defaultViewEmpleados': 'table',
      'defaultViewTareas': 'table',
      'defaultViewPlanillas': 'table',
      'defaultViewAsistencias': 'table',
      'defaultViewConfiguracion': 'table',
      transitionSpeed: 1, // Default to normal speed
      // Chat UI colors
      chatAgentMessageColor: '#FFFFFF',
      chatOwnMessageColor: '#D1E8FF',
      chatInputBoxColor: '#FFFFFF',
      chatAccentColor: '#1976D2',
      chatBackgroundColor: '#F4F4F4',
      // Chat UI fonts
      chatFontColor: '#000000',
      chatFontFamily: '',
      chatFontSize: 14,
    }

    const loadedSettings = loadSettingsFromLocalStorage()
    if (loadedSettings) {
      for (const key of appearanceSettingKeys) {
        // Only update if the key exists in loadedSettings and is an appearance key
        if (loadedSettings.hasOwnProperty(key)) {
          defaultState[key] = loadedSettings[key]
        }
      }
    }
    return defaultState
  },

  actions: {
    // Non-appearance related actions
    toggleSidebar() {
      this.sidebarOpen = !this.sidebarOpen
      // No need to save appearance state here
    },
    closeSidebar() {
      this.sidebarOpen = false
    },
    openSidebar() {
      this.sidebarOpen = true
    },

    // Appearance related actions
    setPrimaryColor(color) {
      this.primaryColor = color
      _saveAppearanceState(this)
    },
    setSecondaryColor(color) {
      this.secondaryColor = color
      _saveAppearanceState(this)
    },
    setWarningColor(color) {
      this.warningColor = color
      _saveAppearanceState(this)
    },
    setFontFamily(font) {
      this.fontFamily = font
      _saveAppearanceState(this)
    },
    setFontSize(size) {
      this.fontSize = Number(size) // Ensure fontSize is stored as a number
      _saveAppearanceState(this)
    },
    setAnimationsEnabled(enabled) {
      this.animationsEnabled = !!enabled // Ensure boolean
      _saveAppearanceState(this)
    },
    setBackgroundColor(color) {
      this.backgroundColor = color
      _saveAppearanceState(this)
    },
    setTheme(theme) {
      this.theme = theme
      _saveAppearanceState(this)
    },
    toggleTheme() {
      this.theme = this.theme === 'light' ? 'dark' : 'light'
      _saveAppearanceState(this)
    },

    // Actions for module-specific accent colors
    setAccentColorEmpleados(color) {
      this.accentColorEmpleados = color
      _saveAppearanceState(this)
    },
    setAccentColorTareas(color) {
      this.accentColorTareas = color
      _saveAppearanceState(this)
    },
    setAccentColorPlanillas(color) {
      this.accentColorPlanillas = color
      _saveAppearanceState(this)
    },
    setAccentColorAsistencias(color) {
      this.accentColorAsistencias = color
      _saveAppearanceState(this)
    },
    setAccentColorConfiguracion(color) {
      this.accentColorConfiguracion = color
      _saveAppearanceState(this)
    },
    setAccentColorChat(color) {
      this.accentColorChat = color;
      _saveAppearanceState(this);
    },

    // Actions for per-module table background colors
    setTableBgColorEmpleados(color) {
      this.tableBgColorEmpleados = color
      _saveAppearanceState(this)
    },
    setTableBgColorTareas(color) {
      this.tableBgColorTareas = color
      _saveAppearanceState(this)
    },
    setTableBgColorPlanillas(color) {
      this.tableBgColorPlanillas = color
      _saveAppearanceState(this)
    },
    setTableBgColorAsistencias(color) {
      this.tableBgColorAsistencias = color
      _saveAppearanceState(this)
    },
    setTableBgColorConfiguracion(color) {
      this.tableBgColorConfiguracion = color
      _saveAppearanceState(this)
    },
    setBackgroundColorChat(color) {
      this.backgroundColorChat = color;
      _saveAppearanceState(this);
    },
    setDesktopNavbarPersistent(enabled) {
      this.desktopNavbarPersistent = !!enabled // Ensure boolean
      _saveAppearanceState(this)
    },

    // Actions for default module views
    setDefaultViewEmpleados(view) {
      this.defaultViewEmpleados = view
      _saveAppearanceState(this)
    },
    setDefaultViewTareas(view) {
      this.defaultViewTareas = view
      _saveAppearanceState(this)
    },
    setDefaultViewPlanillas(view) {
      this.defaultViewPlanillas = view
      _saveAppearanceState(this)
    },
    setDefaultViewAsistencias(view) {
      this.defaultViewAsistencias = view
      _saveAppearanceState(this)
    },
    setDefaultViewConfiguracion(view) {
      this.defaultViewConfiguracion = view
      _saveAppearanceState(this)
    },

    // Action for transition speed
    setTransitionSpeed(newSpeed) {
      this.transitionSpeed = Number(newSpeed) // Ensure it's a number
      _saveAppearanceState(this)
    },

    // Actions for chat UI colors
    setChatAgentMessageColor(color) {
      this.chatAgentMessageColor = color
      _saveAppearanceState(this)
    },
    setChatOwnMessageColor(color) {
      this.chatOwnMessageColor = color
      _saveAppearanceState(this)
    },
    setChatInputBoxColor(color) {
      this.chatInputBoxColor = color
      _saveAppearanceState(this)
    },
    setChatAccentColor(color) {
      this.chatAccentColor = color
      _saveAppearanceState(this)
    },
    setChatBackgroundColor(color) {
      this.chatBackgroundColor = color
      _saveAppearanceState(this)
    },

    // Actions for chat UI fonts
    setChatFontColor(color) {
      this.chatFontColor = color
      _saveAppearanceState(this)
    },
    setChatFontFamily(font) {
      this.chatFontFamily = font
      _saveAppearanceState(this)
    },
    setChatFontSize(size) {
      this.chatFontSize = Number(size)
      _saveAppearanceState(this)
    },
  },
})

// Note: The prompt mentioned using store's `subscribe` method.
// The chosen approach of calling _saveAppearanceState within each relevant action
// achieves the "save on change" requirement for an options store when modifications
// are done through actions. Pinia's $subscribe method is typically attached to a store instance
// after its creation (e.g., in main.js or a plugin) to react to all state changes,
// including direct state manipulations (if any) or changes from multiple actions.
// For this subtask, modifying actions is a self-contained way within this file.
// If global subscription to all state changes (even those not via these specific actions)
// is strictly required by "subscribe method", then a Pinia plugin or setup in main.js
// would be the more idiomatic Pinia approach. This solution prioritizes keeping logic
// within this file and reacting to changes triggered by the defined actions.
