import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

export interface ThemeColors {
  primary: string;
  secondary: string;
  accent: string;
  background: string;
  surface: string;
  text: string;
  textSecondary: string;
}

export interface Theme {
  id: string;
  name: string;
  colors: ThemeColors;
  borderRadius: string;
  shadow: string;
  fonts: {
    primary: string;
    secondary: string;
    mono: string;
  };
}

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private currentThemeSubject = new BehaviorSubject<Theme>(this.getDefaultTheme());
  public currentTheme$ = this.currentThemeSubject.asObservable();

  private readonly STORAGE_KEY = 'cloudnsure-theme';

  constructor() {
    this.loadThemeFromStorage();
  }

  // Default theme
  private getDefaultTheme(): Theme {
    return {
      id: 'default',
      name: 'Default Blue',
      colors: {
        primary: '#0ea5e9',
        secondary: '#64748b',
        accent: '#8b5cf6',
        background: '#f8fafc',
        surface: '#ffffff',
        text: '#1f2937',
        textSecondary: '#6b7280'
      },
      borderRadius: '0.5rem',
      shadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)',
      fonts: {
        primary: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        secondary: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        mono: 'JetBrains Mono, "Fira Code", Consolas, monospace'
      }
    };
  }

  // Predefined themes
  getThemes(): Theme[] {
    return [
      this.getDefaultTheme(),
      {
        id: 'purple',
        name: 'Purple Dream',
        colors: {
          primary: '#8b5cf6',
          secondary: '#64748b',
          accent: '#ec4899',
          background: '#faf5ff',
          surface: '#ffffff',
          text: '#1f2937',
          textSecondary: '#6b7280'
        },
        borderRadius: '0.75rem',
        shadow: '0 10px 15px -3px rgba(139, 92, 246, 0.1)',
        fonts: {
          primary: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          secondary: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          mono: 'JetBrains Mono, "Fira Code", Consolas, monospace'
        }
      },
      {
        id: 'green',
        name: 'Forest Green',
        colors: {
          primary: '#10b981',
          secondary: '#64748b',
          accent: '#f59e0b',
          background: '#f0fdf4',
          surface: '#ffffff',
          text: '#1f2937',
          textSecondary: '#6b7280'
        },
        borderRadius: '0.375rem',
        shadow: '0 10px 15px -3px rgba(16, 185, 129, 0.1)',
        fonts: {
          primary: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          secondary: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          mono: 'JetBrains Mono, "Fira Code", Consolas, monospace'
        }
      },
      {
        id: 'orange',
        name: 'Sunset Orange',
        colors: {
          primary: '#f59e0b',
          secondary: '#64748b',
          accent: '#ef4444',
          background: '#fffbeb',
          surface: '#ffffff',
          text: '#1f2937',
          textSecondary: '#6b7280'
        },
        borderRadius: '1rem',
        shadow: '0 10px 15px -3px rgba(245, 158, 11, 0.1)',
        fonts: {
          primary: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          secondary: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          mono: 'JetBrains Mono, "Fira Code", Consolas, monospace'
        }
      },
      {
        id: 'dark',
        name: 'Dark Mode',
        colors: {
          primary: '#3b82f6',
          secondary: '#9ca3af',
          accent: '#8b5cf6',
          background: '#111827',
          surface: '#1f2937',
          text: '#f9fafb',
          textSecondary: '#d1d5db'
        },
        borderRadius: '0.5rem',
        shadow: '0 10px 15px -3px rgba(0, 0, 0, 0.3)',
        fonts: {
          primary: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          secondary: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          mono: 'JetBrains Mono, "Fira Code", Consolas, monospace'
        }
      }
    ];
  }

  // Get current theme
  getCurrentTheme(): Theme {
    return this.currentThemeSubject.value;
  }

  // Apply theme
  applyTheme(theme: Theme): void {
    this.currentThemeSubject.next(theme);
    this.saveThemeToStorage(theme);
    this.updateCSSVariables(theme);
  }

  // Select theme by ID
  selectTheme(themeId: string): void {
    const theme = this.getThemes().find(t => t.id === themeId);
    if (theme) {
      this.applyTheme(theme);
    }
  }

  // Update theme colors
  updateThemeColors(colors: Partial<ThemeColors>): void {
    const currentTheme = this.getCurrentTheme();
    const updatedTheme = {
      ...currentTheme,
      colors: { ...currentTheme.colors, ...colors }
    };
    this.applyTheme(updatedTheme);
  }

  // Update theme fonts
  updateThemeFonts(fonts: Partial<Theme['fonts']>): void {
    const currentTheme = this.getCurrentTheme();
    const updatedTheme = {
      ...currentTheme,
      fonts: { ...currentTheme.fonts, ...fonts }
    };
    this.applyTheme(updatedTheme);
  }

  // Update theme properties
  updateThemeProperty(property: keyof Theme, value: any): void {
    const currentTheme = this.getCurrentTheme();
    const updatedTheme = {
      ...currentTheme,
      [property]: value
    };
    this.applyTheme(updatedTheme);
  }

  // Reset to default theme
  resetToDefault(): void {
    this.applyTheme(this.getDefaultTheme());
  }

  // Export theme
  exportTheme(): string {
    return JSON.stringify(this.getCurrentTheme(), null, 2);
  }

  // Import theme
  importTheme(themeJson: string): boolean {
    try {
      const theme = JSON.parse(themeJson) as Theme;
      if (this.validateTheme(theme)) {
        this.applyTheme(theme);
        return true;
      }
      return false;
    } catch (error) {
      console.error('Invalid theme JSON:', error);
      return false;
    }
  }

  // Validate theme structure
  private validateTheme(theme: any): theme is Theme {
    return (
      theme &&
      typeof theme.id === 'string' &&
      typeof theme.name === 'string' &&
      theme.colors &&
      typeof theme.colors.primary === 'string' &&
      typeof theme.colors.secondary === 'string' &&
      typeof theme.colors.accent === 'string' &&
      typeof theme.colors.background === 'string' &&
      typeof theme.colors.surface === 'string' &&
      typeof theme.colors.text === 'string' &&
      typeof theme.colors.textSecondary === 'string'
    );
  }

  // Update CSS custom properties
  private updateCSSVariables(theme: Theme): void {
    const root = document.documentElement;
    
    // Update color variables
    root.style.setProperty('--theme-primary', theme.colors.primary);
    root.style.setProperty('--theme-secondary', theme.colors.secondary);
    root.style.setProperty('--theme-accent', theme.colors.accent);
    root.style.setProperty('--theme-background', theme.colors.background);
    root.style.setProperty('--theme-surface', theme.colors.surface);
    root.style.setProperty('--theme-text', theme.colors.text);
    root.style.setProperty('--theme-text-secondary', theme.colors.textSecondary);
    
    // Update other properties
    root.style.setProperty('--theme-border-radius', theme.borderRadius);
    root.style.setProperty('--theme-shadow', theme.shadow);
    root.style.setProperty('--theme-font-primary', theme.fonts.primary);
    root.style.setProperty('--theme-font-secondary', theme.fonts.secondary);
    root.style.setProperty('--theme-font-mono', theme.fonts.mono);

    // Update body class for theme-specific styling
    document.body.className = document.body.className.replace(/theme-\w+/g, '');
    document.body.classList.add(`theme-${theme.id}`);
  }

  // Load theme from localStorage
  private loadThemeFromStorage(): void {
    try {
      const stored = localStorage.getItem(this.STORAGE_KEY);
      if (stored) {
        const theme = JSON.parse(stored) as Theme;
        if (this.validateTheme(theme)) {
          this.currentThemeSubject.next(theme);
          this.updateCSSVariables(theme);
        }
      } else {
        // Apply default theme on first load
        this.updateCSSVariables(this.getDefaultTheme());
      }
    } catch (error) {
      console.error('Error loading theme from storage:', error);
      this.updateCSSVariables(this.getDefaultTheme());
    }
  }

  // Save theme to localStorage
  private saveThemeToStorage(theme: Theme): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(theme));
    } catch (error) {
      console.error('Error saving theme to storage:', error);
    }
  }

  // Get color presets for color picker
  getColorPresets(): { name: string; value: string }[] {
    return [
      { name: 'Blue', value: '#0ea5e9' },
      { name: 'Purple', value: '#8b5cf6' },
      { name: 'Green', value: '#10b981' },
      { name: 'Orange', value: '#f59e0b' },
      { name: 'Red', value: '#ef4444' },
      { name: 'Pink', value: '#ec4899' },
      { name: 'Indigo', value: '#6366f1' },
      { name: 'Teal', value: '#14b8a6' },
      { name: 'Yellow', value: '#eab308' },
      { name: 'Gray', value: '#64748b' }
    ];
  }

  // Get font options
  getFontOptions(): { name: string; value: string }[] {
    return [
      { name: 'Inter', value: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Poppins', value: 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Roboto', value: 'Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' },
      { name: 'Open Sans', value: '"Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Lato', value: 'Lato, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Montserrat', value: 'Montserrat, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Source Sans Pro', value: '"Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
      { name: 'Nunito', value: 'Nunito, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }
    ];
  }
}