import { Component, OnInit, OnDestroy } from '@angular/core';
import { ThemeService, Theme } from '../../../services/theme.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-theme-customization',
  templateUrl: './theme-customization.component.html',
  styleUrls: ['./theme-customization.component.scss']
})
export class ThemeCustomizationComponent implements OnInit, OnDestroy {
  themes: Theme[] = [];
  currentTheme: Theme | null = null;
  customTheme: Partial<Theme> = {
    colors: {
      primary: '#0ea5e9',
      secondary: '#64748b',
      accent: '#8b5cf6',
      background: '#f8fafc',
      surface: '#ffffff',
      text: '#111827',
      textSecondary: '#6b7280'
    },
    fonts: {
      primary: 'Inter',
      secondary: 'Poppins',
      mono: 'JetBrains Mono'
    },
    borderRadius: '0.75rem',
    shadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)'
  };
  isCustomizing = false;
  showAdvanced = false;
  
  private themeSubscription: Subscription = new Subscription();

  // Color presets and font options from service
  colorPresets = this.themeService.getColorPresets();
  fontOptions = this.themeService.getFontOptions();

  constructor(private themeService: ThemeService) {}

  ngOnInit(): void {
    this.themes = this.themeService.getThemes();
    this.currentTheme = this.themeService.getCurrentTheme();
    
    this.themeSubscription = this.themeService.currentTheme$.subscribe(theme => {
      this.currentTheme = theme;
    });

    this.initializeCustomTheme();
  }

  ngOnDestroy(): void {
    this.themeSubscription.unsubscribe();
  }

  selectTheme(themeId: string): void {
    this.themeService.selectTheme(themeId);
    this.isCustomizing = false;
  }

  startCustomizing(): void {
    this.isCustomizing = true;
    this.initializeCustomTheme();
  }

  cancelCustomizing(): void {
    this.isCustomizing = false;
    this.initializeCustomTheme();
  }

  applyCustomTheme(): void {
    if (this.customTheme.colors && this.customTheme.fonts) {
      const customTheme: Theme = {
        id: 'custom',
        name: 'Custom Theme',
        colors: this.customTheme.colors,
        fonts: this.customTheme.fonts,
        borderRadius: this.customTheme.borderRadius || '0.5rem',
        shadow: this.customTheme.shadow || '0 10px 15px -3px rgba(0, 0, 0, 0.1)'
      };
      this.themeService.applyTheme(customTheme);
    }
    this.isCustomizing = false;
  }

  resetToDefault(): void {
    this.themeService.resetToDefault();
  }

  exportTheme(): void {
    const themeJson = this.themeService.exportTheme();
    this.downloadFile(themeJson, 'theme.json', 'application/json');
  }

  importTheme(event: any): void {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        if (this.themeService.importTheme(content)) {
          alert('Theme imported successfully!');
        } else {
          alert('Failed to import theme. Please check the file format.');
        }
      };
      reader.readAsText(file);
    }
  }

  private initializeCustomTheme(): void {
    if (this.currentTheme) {
      this.customTheme = {
        colors: { 
          primary: this.currentTheme.colors.primary,
          secondary: this.currentTheme.colors.secondary,
          accent: this.currentTheme.colors.accent,
          background: this.currentTheme.colors.background,
          surface: this.currentTheme.colors.surface,
          text: this.currentTheme.colors.text,
          textSecondary: this.currentTheme.colors.textSecondary
        },
        fonts: { 
          primary: this.currentTheme.fonts.primary,
          secondary: this.currentTheme.fonts.secondary,
          mono: this.currentTheme.fonts.mono
        },
        borderRadius: this.currentTheme.borderRadius,
        shadow: this.currentTheme.shadow
      };
    } else {
      // Default values if no current theme
      this.customTheme = {
        colors: {
          primary: '#0ea5e9',
          secondary: '#64748b',
          accent: '#8b5cf6',
          background: '#f8fafc',
          surface: '#ffffff',
          text: '#111827',
          textSecondary: '#6b7280'
        },
        fonts: {
          primary: 'Inter',
          secondary: 'Poppins',
          mono: 'JetBrains Mono'
        },
        borderRadius: '0.75rem',
        shadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)'
      };
    }
  }

  private downloadFile(content: string, filename: string, contentType: string): void {
    const blob = new Blob([content], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
    window.URL.revokeObjectURL(url);
  }

  // Color picker methods
  onColorChange(colorType: string, value: string): void {
    if (!this.customTheme.colors) {
      this.customTheme.colors = {
        primary: '#0ea5e9',
        secondary: '#64748b',
        accent: '#8b5cf6',
        background: '#f8fafc',
        surface: '#ffffff',
        text: '#111827',
        textSecondary: '#6b7280'
      };
    }
    (this.customTheme.colors as any)[colorType] = value;
  }

  // Font picker methods
  onFontChange(fontType: string, value: string): void {
    if (!this.customTheme.fonts) {
      this.customTheme.fonts = {
        primary: 'Inter',
        secondary: 'Poppins',
        mono: 'JetBrains Mono'
      };
    }
    (this.customTheme.fonts as any)[fontType] = value;
  }

  // Border radius methods
  onBorderRadiusChange(value: string): void {
    this.customTheme.borderRadius = value;
  }

  // Shadow methods
  onShadowChange(value: string): void {
    this.customTheme.shadow = value;
  }

  // Preview methods
  previewTheme(): void {
    if (this.isCustomizing && this.customTheme.colors && this.customTheme.fonts) {
      const previewTheme: Theme = {
        id: 'preview',
        name: 'Preview Theme',
        colors: this.customTheme.colors,
        fonts: this.customTheme.fonts,
        borderRadius: this.customTheme.borderRadius || '0.5rem',
        shadow: this.customTheme.shadow || '0 10px 15px -3px rgba(0, 0, 0, 0.1)'
      };
      this.themeService.applyTheme(previewTheme);
    }
  }

  // Utility methods
  getColorValue(colorType: string): string {
    if (this.customTheme.colors) {
      return (this.customTheme.colors as any)[colorType] || '#0ea5e9';
    }
    return '#0ea5e9';
  }

  getFontValue(fontType: string): string {
    if (this.customTheme.fonts) {
      return (this.customTheme.fonts as any)[fontType] || 'Inter';
    }
    return 'Inter';
  }

  getBorderRadiusValue(): string {
    return this.customTheme.borderRadius || '0.75rem';
  }

  getShadowValue(): string {
    return this.customTheme.shadow || '0 10px 15px -3px rgba(0, 0, 0, 0.1)';
  }

  getShadowValueNumber(): string {
    const shadowValue = this.getShadowValue();
    const match = shadowValue.match(/\d+/);
    return match ? match[0] : '10';
  }
}
