/**
 * Theme Management Service
 * Manages sitewide theme selection and persistence
 */

export type ThemeType = 'blue' | 'neon-green' | 'gold';

export interface Theme {
  id: ThemeType;
  name: string;
  description: string;
  backgroundColor: string;
  accentColor: string;
  textColor: string;
  borderColor: string;
  hoverColor: string;
  cssFile: string;
}

export interface SiteThemeConfig {
  currentTheme: ThemeType;
  lastChangedBy: number;
  lastChangedAt: Date;
  availableThemes: Theme[];
}

// Define all available themes
const THEMES: Record<ThemeType, Theme> = {
  blue: {
    id: 'blue',
    name: 'White + Blue Accents',
    description: 'Clean white background with professional blue accents',
    backgroundColor: '#ffffff',
    accentColor: '#2563eb',
    textColor: '#1f2937',
    borderColor: '#e5e7eb',
    hoverColor: '#1d4ed8',
    cssFile: '/themes/blue.css',
  },
  'neon-green': {
    id: 'neon-green',
    name: 'White + Neon Green Accents',
    description: 'Bright white background with vibrant neon green accents',
    backgroundColor: '#ffffff',
    accentColor: '#39ff14',
    textColor: '#1f2937',
    borderColor: '#e5e7eb',
    hoverColor: '#2ce60f',
    cssFile: '/themes/neon-green.css',
  },
  gold: {
    id: 'gold',
    name: 'Black + Gold Accents',
    description: 'Dark black background with elegant gold accents',
    backgroundColor: '#000000',
    accentColor: '#fbbf24',
    textColor: '#ffffff',
    borderColor: '#374151',
    hoverColor: '#f59e0b',
    cssFile: '/themes/gold.css',
  },
};

// In-memory storage for current theme (in production, this would be in database)
let currentSiteTheme: ThemeType = 'blue';
let themeHistory: Array<{ theme: ThemeType; changedBy: number; changedAt: Date }> = [];

/**
 * Get all available themes
 */
export function getAllThemes(): Theme[] {
  return Object.values(THEMES);
}

/**
 * Get theme by ID
 */
export function getTheme(themeId: ThemeType): Theme | undefined {
  return THEMES[themeId];
}

/**
 * Get current sitewide theme
 */
export function getCurrentTheme(): Theme {
  return THEMES[currentSiteTheme];
}

/**
 * Get current theme ID
 */
export function getCurrentThemeId(): ThemeType {
  return currentSiteTheme;
}

/**
 * Change sitewide theme
 */
export function changeTheme(themeId: ThemeType, changedByUserId: number): boolean {
  if (!THEMES[themeId]) {
    console.error(`[ThemeService] Invalid theme ID: ${themeId}`);
    return false;
  }

  const previousTheme = currentSiteTheme;
  currentSiteTheme = themeId;

  // Log theme change
  themeHistory.push({
    theme: themeId,
    changedBy: changedByUserId,
    changedAt: new Date(),
  });

  console.log(`[ThemeService] Theme changed from ${previousTheme} to ${themeId} by user ${changedByUserId}`);
  return true;
}

/**
 * Get theme history
 */
export function getThemeHistory(): Array<{ theme: ThemeType; changedBy: number; changedAt: Date }> {
  return themeHistory;
}

/**
 * Get theme CSS variables
 */
export function getThemeCSSVariables(themeId: ThemeType): Record<string, string> {
  const theme = THEMES[themeId];
  if (!theme) return {};

  return {
    '--theme-bg': theme.backgroundColor,
    '--theme-accent': theme.accentColor,
    '--theme-text': theme.textColor,
    '--theme-border': theme.borderColor,
    '--theme-hover': theme.hoverColor,
  };
}

/**
 * Get theme configuration
 */
export function getSiteThemeConfig(): SiteThemeConfig {
  const lastChange = themeHistory[themeHistory.length - 1];

  return {
    currentTheme: currentSiteTheme,
    lastChangedBy: lastChange?.changedBy || 0,
    lastChangedAt: lastChange?.changedAt || new Date(),
    availableThemes: Object.values(THEMES),
  };
}

/**
 * Reset to default theme
 */
export function resetToDefaultTheme(changedByUserId: number): boolean {
  return changeTheme('blue', changedByUserId);
}

/**
 * Get theme by name
 */
export function getThemeByName(name: string): Theme | undefined {
  return Object.values(THEMES).find((t) => t.name.toLowerCase() === name.toLowerCase());
}

/**
 * Validate theme ID
 */
export function isValidThemeId(themeId: string): themeId is ThemeType {
  return themeId in THEMES;
}

/**
 * Get theme colors for UI
 */
export function getThemeColors(themeId: ThemeType): {
  bg: string;
  accent: string;
  text: string;
  border: string;
} {
  const theme = THEMES[themeId];
  if (!theme) {
    const defaultTheme = THEMES.blue;
    return {
      bg: defaultTheme.backgroundColor,
      accent: defaultTheme.accentColor,
      text: defaultTheme.textColor,
      border: defaultTheme.borderColor,
    };
  }

  return {
    bg: theme.backgroundColor,
    accent: theme.accentColor,
    text: theme.textColor,
    border: theme.borderColor,
  };
}

/**
 * Get theme contrast ratio (for accessibility)
 */
export function getThemeContrast(themeId: ThemeType): 'high' | 'medium' | 'low' {
  const theme = THEMES[themeId];
  if (!theme) return 'medium';

  // Simple contrast calculation based on brightness
  const bgBrightness = theme.backgroundColor === '#ffffff' ? 255 : 0;
  const textBrightness = theme.textColor === '#ffffff' ? 255 : 0;

  const contrast = Math.abs(bgBrightness - textBrightness);

  if (contrast > 200) return 'high';
  if (contrast > 100) return 'medium';
  return 'low';
}
