import less from 'less';
let currentTheme: Record<string, string> = {};

// 初始化主题
export async function initializeTheme(themeMode: string = 'default') {
  try {
    const theme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
    currentTheme = { ...theme };
    applyThemeVariables(); // 应用动态样式
    console.log(`Initialized theme: ${themeMode}`);
  } catch (error) {
    console.error(`Failed to initialize theme: ${themeMode}`, error);
  }
}

// 动态切换主题
export async function switchTheme(themeMode: string) {
  try {
    const newTheme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
    currentTheme = { ...newTheme };
    applyThemeVariables(); // 应用动态样式
    console.log(`Switched to theme: ${themeMode}`);
  } catch (error) {
    console.error(`Failed to switch theme: ${themeMode}`, error);
  }
}

// 动态更新单个主题变量
export function updateThemeVariable(key: string, value: string) {
  currentTheme[key] = value;
  applyThemeVariables(); // 应用动态样式
  console.log(`Updated ${key} to ${value}`);
}

// 应用动态样式
function applyThemeVariables() {
  // 应用到 Less
  applyLessVariables();

  // 应用到 Stylus
  applyStylusVariables();
}

// 应用动态 Less 变量
function applyLessVariables() {
  // 将当前主题变量转换为 Less 的格式
  const lessVariables = Object.entries(currentTheme).reduce(
    (acc, [key, value]) => ({ ...acc, [`@${key}`]: value }),
    {},
  );

  // 使用 Less.js 动态更新变量
  less
    .modifyVars(lessVariables)
    .then(() => {
      console.log('Less variables applied successfully:', lessVariables);
    })
    .catch((error) => {
      console.error('Failed to apply Less variables:', error);
    });
}
// 应用动态 Stylus 变量
function applyStylusVariables() {
  const stylusVariables = Object.entries(currentTheme)
    .map(([key, value]) => `$${key}: ${value};`)
    .join('\n');

  const existingStyleElement = document.getElementById('dynamic-stylus-styles');
  if (existingStyleElement) {
    existingStyleElement.remove();
  }

  const styleElement = document.createElement('style');
  styleElement.id = 'dynamic-stylus-styles';
  styleElement.textContent = stylusVariables;
  document.head.appendChild(styleElement);

  console.log('Stylus variables applied successfully.');
}

// 获取当前主题
export function getCurrentTheme() {
  return { ...currentTheme };
}
