/**
 * 系统设置状态管理
 * 作者: 阿瑞
 * 功能: 管理系统设置，包括主题模式等配置
 * 版本: 1.3.3
 */

import { create } from 'zustand';

/**
 * 设置存储键名枚举
 */
export enum StorageEnum {
  Settings = 'saas-settings'
}

/**
 * 主题模式枚举
 */
export enum ThemeMode {
  Light = 'light',
  Dark = 'dark'
}

/**
 * 从本地存储获取数据
 * @param key 存储键名
 * @returns 解析后的数据或null
 */
export const getItem = <T>(key: StorageEnum): T | null => {
  if (typeof window === 'undefined') return null;

  try {
    const result = window.localStorage.getItem(key);
    return result ? JSON.parse(result) : null;
  } catch (error) {
    console.error('获取本地存储失败:', error);
    return null;
  }
};

/**
 * 保存数据到本地存储
 * @param key 存储键名
 * @param value 要存储的数据
 */
export const setItem = <T>(key: StorageEnum, value: T): void => {
  if (typeof window === 'undefined') return;
  
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    console.error('保存到本地存储失败:', error);
  }
};

/**
 * 从本地存储删除数据
 * @param key 存储键名
 */
export const removeItem = (key: StorageEnum): void => {
  if (typeof window === 'undefined') return;
  
  try {
    localStorage.removeItem(key);
  } catch (error) {
    console.error('从本地存储删除失败:', error);
  }
};

/**
 * 主题设置类型
 */
interface ThemeSettings {
  themeMode: ThemeMode;
}

/**
 * 设置状态仓库类型
 */
interface SettingStore {
  settings: ThemeSettings;
  actions: {
    setSettings: (settings: Partial<ThemeSettings>) => void;
    setThemeMode: (themeMode: ThemeMode) => void;
    toggleThemeMode: () => void;
    clearSettings: () => void;
  };
}

/**
 * 默认主题设置
 */
const defaultSettings: ThemeSettings = { 
  themeMode: ThemeMode.Light
};

/**
 * 获取初始主题设置
 * 优先从本地存储读取，如果没有则使用默认设置
 * 注意：服务器端渲染时总是返回默认设置
 */
function getInitialSettings(): ThemeSettings {
  if (typeof window === 'undefined') {
    return defaultSettings;
  }
  
  try {
    const storedSettings = getItem<ThemeSettings>(StorageEnum.Settings);
    if (storedSettings?.themeMode) {
      return storedSettings;
    }
  } catch (error) {
    console.error('读取主题设置失败:', error);
  }
  
  return defaultSettings;
}

/**
 * 应用主题到DOM
 * 仅在客户端组件中通过useEffect调用
 * @param themeMode 主题模式
 */
const applyThemeToDOM = (themeMode: ThemeMode): void => {
  if (typeof document === 'undefined') return;

  console.log('settingStore: 应用主题', themeMode);
  
  // 强制移除所有主题相关类名，然后添加当前主题类名
  document.body.classList.remove('dark-theme', 'light-theme');
  document.body.classList.add(themeMode === ThemeMode.Dark ? 'dark-theme' : 'light-theme');

  // 为移动设备设置meta主题色
  const metaThemeColor = document.querySelector('meta[name="theme-color"]');
  if (metaThemeColor) {
    metaThemeColor.setAttribute(
      'content',
      themeMode === ThemeMode.Dark ? '#0a1128' : '#f6f9fc'
    );
  }
};

// 移除模块初始化时的DOM操作，避免服务器和客户端水合不匹配
// 这部分逻辑将由ThemeProvider组件在客户端水合后处理

/**
 * 创建设置状态管理器
 */
const useSettingStore = create<SettingStore>((set, get) => ({
  // 初始化设置
  settings: getInitialSettings(),

  actions: {
    /**
     * 更新设置
     * @param newSettings 新的设置值
     */
    setSettings: (newSettings) => {
      const currentSettings = get().settings;
      const updatedSettings = { ...currentSettings, ...newSettings };

      set({ settings: updatedSettings });
      setItem(StorageEnum.Settings, updatedSettings);

      // 检查是否包含主题设置，如果有则应用
      // 仅在客户端环境下应用DOM变更
      if (typeof window !== 'undefined' && 
          newSettings.themeMode !== undefined &&
          newSettings.themeMode !== currentSettings.themeMode) {
        applyThemeToDOM(newSettings.themeMode);
      }
    },

    /**
     * 设置主题模式
     * @param themeMode 主题模式
     */
    setThemeMode: (themeMode) => {
      const currentSettings = get().settings;

      // 如果主题没有变化，则不进行操作
      if (currentSettings.themeMode === themeMode) return;

      // 更新设置
      get().actions.setSettings({ themeMode });
    },

    /**
     * 切换主题模式
     * 在亮色和暗色之间切换
     */
    toggleThemeMode: () => {
      const currentTheme = get().settings.themeMode;
      const newTheme = currentTheme === ThemeMode.Light ? ThemeMode.Dark : ThemeMode.Light;

      console.log('切换主题:', currentTheme, '->', newTheme);
      get().actions.setThemeMode(newTheme);
    },

    /**
     * 清除设置并恢复默认值
     */
    clearSettings: () => {
      set({ settings: defaultSettings });
      removeItem(StorageEnum.Settings);
      
      // 仅在客户端环境下应用DOM变更
      if (typeof window !== 'undefined') {
        applyThemeToDOM(defaultSettings.themeMode);
      }
    },
  },
}));

/**
 * 导出便捷的Hook
 */
export const useSettings = () => useSettingStore((state) => state.settings);
export const useSettingActions = () => useSettingStore((state) => state.actions);
export const useThemeMode = () => useSettingStore((state) => state.settings.themeMode);

export default useSettingStore;
