/**
 * ==========================================================================
 * THEME SWITCHER COMPONENT
 * ==========================================================================
 * Interactive component for runtime theme switching.
 * Supports predefined themes, custom colors, and dark mode toggle.
 * Provides color validation and preview functionality.
 * ==========================================================================
 */

import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil, debounceTime, distinctUntilChanged } from 'rxjs/operators';

import { ThemeService, ThemeConfig, ThemeState } from '../../../core/services/theme.service';

@Component({
  selector: 'app-theme-switcher',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <!--
    ==========================================================================
    THEME SWITCHER TEMPLATE
    ==========================================================================
    Interactive UI for runtime theme switching with Material Design 3 styling
    ==========================================================================
    -->

    <div class="theme-switcher">
      <!-- Theme Switcher Header -->
      <div class="theme-switcher__header">
        <h3 class="theme-switcher__title">Theme Settings</h3>
        <p class="theme-switcher__subtitle">Customize your app's appearance</p>
      </div>

      <!-- Dark Mode Toggle -->
      <div class="theme-switcher__section">
        <div class="theme-switcher__option">
          <label class="theme-switcher__label">
            <input 
              type="checkbox" 
              class="theme-switcher__checkbox"
              [checked]="isDarkMode"
              (change)="onDarkModeToggle()"
              [disabled]="isApplyingTheme"
            >
            <span class="theme-switcher__checkbox-custom"></span>
            <span class="theme-switcher__text">Dark mode</span>
          </label>
        </div>
      </div>

      <!-- Predefined Themes -->
      <div class="theme-switcher__section">
        <h4 class="theme-switcher__section-title">Predefined Themes</h4>
        <div class="theme-grid">
          @for (theme of availableThemes; track theme.name) {
            <div 
              class="theme-card"
              [class.theme-card--active]="isThemeActive(theme.name)"
              [class.theme-card--disabled]="isApplyingTheme"
              (click)="onThemeChange(theme.name)"
            >
            <div class="theme-card__preview">
              <div 
                class="theme-card__color-primary" 
                [style.backgroundColor]="theme.primary"
              ></div>
              <div class="theme-card__color-details">
                <div 
                  class="theme-card__color-secondary" 
                  [style.backgroundColor]="theme.secondary || '#625B71'"
                ></div>
                <div 
                  class="theme-card__color-tertiary" 
                  [style.backgroundColor]="theme.tertiary || '#7D5260'"
                ></div>
              </div>
            </div>
            <span class="theme-card__name">{{ getThemeDisplayName(theme.name) }}</span>
            @if (isThemeActive(theme.name)) {
              <div class="theme-card__active-indicator">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
                </svg>
              </div>
            }
            </div>
          }
        </div>
      </div>

      <!-- Custom Color Section -->
      <div class="theme-switcher__section">
        <div class="theme-switcher__section-header">
          <h4 class="theme-switcher__section-title">Custom Color</h4>
          <button 
            type="button" 
            class="theme-switcher__toggle-btn"
            [class.theme-switcher__toggle-btn--active]="showCustomColorPanel"
            (click)="onToggleCustomPanel()"
            [disabled]="isApplyingTheme"
          >
            {{ showCustomColorPanel ? 'Hide' : 'Customize' }}
          </button>
        </div>

        <div 
          class="theme-switcher__custom-panel"
          [class.theme-switcher__custom-panel--visible]="showCustomColorPanel"
        >
          <!-- Color Input -->
          <div class="custom-color-input">
            <label class="custom-color-input__label">Primary Color</label>
            <div class="custom-color-input__container">
              <input 
                type="color" 
                class="custom-color-input__picker"
                [(ngModel)]="customColorInput"
                (input)="onCustomColorChange($any($event.target).value || '')"
                [disabled]="isApplyingTheme"
              >
              <input 
                type="text" 
                class="custom-color-input__text"
                [(ngModel)]="customColorInput"
                (input)="onCustomColorChange($any($event.target).value || '')"
                placeholder="#6750A4"
                [disabled]="isApplyingTheme"
              >
            </div>
          </div>

          <!-- Theme Name Input -->
          <div class="custom-theme-name">
            <label class="custom-theme-name__label">Theme Name (Optional)</label>
            <input 
              type="text" 
              class="custom-theme-name__input"
              [(ngModel)]="customThemeName"
              placeholder="My Custom Theme"
              [disabled]="isApplyingTheme"
            >
          </div>

          <!-- Color Validation -->
          @if (colorValidation) {
            <div 
              class="color-validation"
              [class.color-validation--error]="!colorValidation.isValid"
              [class.color-validation--success]="colorValidation.isValid"
            >
              @if (!colorValidation.isValid) {
                <div class="color-validation__warnings">
                  <div class="color-validation__title">⚠️ Issues found:</div>
                  <ul class="color-validation__list">
                    @for (warning of colorValidation.warnings; track warning) {
                      <li>{{ warning }}</li>
                    }
                  </ul>
                </div>
              }
              @if (colorValidation.recommendations) {
                <div class="color-validation__recommendations">
                  <div class="color-validation__title">💡 Recommendations:</div>
                  <ul class="color-validation__list">
                    @for (rec of colorValidation.recommendations; track rec) {
                      <li>{{ rec }}</li>
                    }
                  </ul>
                </div>
              }
            </div>
          }

          <!-- Color Preview -->
          @if (showColorPreview && colorValidation?.isValid) {
            <div class="color-preview">
              <div class="color-preview__title">Color Preview</div>
              <div class="color-preview__palette">
                @for (color of colorPreview | keyvalue; track color.key) {
                  <div 
                    class="color-preview__swatch" 
                    [style.backgroundColor]="color.value"
                    [style.color]="getContrastTextColor(color.value)"
                  >
                    <span class="color-preview__swatch-label">{{ color.key }}</span>
                  </div>
                }
              </div>
            </div>
          }

          <!-- Apply Button -->
          <div class="custom-color-actions">
            <button 
              type="button" 
              class="custom-color-actions__apply"
              [disabled]="!colorValidation?.isValid || isApplyingTheme"
              (click)="onApplyCustomColor()"
            >
              @if (!isApplyingTheme) {
                <span>Apply Custom Theme</span>
              } @else {
                <span>Applying...</span>
              }
            </button>
          </div>
        </div>
      </div>

      <!-- Reset Section -->
      <div class="theme-switcher__section">
        <button 
          type="button" 
          class="theme-switcher__reset-btn"
          (click)="onResetTheme()"
          [disabled]="isApplyingTheme"
        >
          Reset to Default
        </button>
      </div>

      <!-- Loading Overlay -->
      @if (isApplyingTheme) {
        <div class="theme-switcher__loading-overlay">
          <div class="theme-switcher__loading-spinner"></div>
          <span class="theme-switcher__loading-text">Applying theme...</span>
        </div>
      }
    </div>
  `,
  styleUrls: ['./theme-switcher.component.scss']
})
export class ThemeSwitcherComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  // Component state
  currentTheme: ThemeState = {
    currentTheme: 'default',
    isDark: false,
    primaryColor: '#6750A4',
    customThemes: []
  };
  
  availableThemes: ThemeConfig[] = [];
  isDarkMode = false;
  
  // Custom color input
  customColorInput = '#6750A4';
  customThemeName = 'My Theme';
  colorPreview: { [key: string]: string } = {};
  colorValidation: { isValid: boolean; warnings: string[]; recommendations?: string[]; } | null = null;
  
  // UI state
  showCustomColorPanel = false;
  showColorPreview = false;
  isApplyingTheme = false;

  constructor(private themeService: ThemeService) {}

  ngOnInit(): void {
    this.initializeComponent();
    this.setupSubscriptions();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  // ==========================================================================
  // INITIALIZATION METHODS
  // ==========================================================================

  /**
   * Initializes component state
   */
  private initializeComponent(): void {
    this.availableThemes = this.themeService.getAvailableThemes();
    this.currentTheme = this.themeService.getCurrentTheme();
    this.isDarkMode = this.themeService.isDarkMode();
    this.customColorInput = this.currentTheme.primaryColor;
  }

  /**
   * Sets up reactive subscriptions
   */
  private setupSubscriptions(): void {
    // Listen to theme state changes
    this.themeService.themeState$
      .pipe(takeUntil(this.destroy$))
      .subscribe(themeState => {
        this.currentTheme = themeState;
        this.availableThemes = this.themeService.getAvailableThemes();
      });

    // Listen to dark mode changes
    this.themeService.isDark$
      .pipe(takeUntil(this.destroy$))
      .subscribe(isDark => {
        this.isDarkMode = isDark;
      });
  }

  // ==========================================================================
  // THEME SWITCHING METHODS
  // ==========================================================================

  /**
   * Applies a predefined theme
   * @param themeName - Name of the theme to apply
   */
  onThemeChange(themeName: string): void {
    if (themeName !== this.currentTheme.currentTheme) {
      this.isApplyingTheme = true;
      setTimeout(() => {
        this.themeService.applyTheme(themeName, this.isDarkMode);
        this.isApplyingTheme = false;
      }, 100);
    }
  }

  /**
   * Toggles dark mode
   */
  onDarkModeToggle(): void {
    this.themeService.toggleDarkMode();
  }

  /**
   * Resets to default theme
   */
  onResetTheme(): void {
    this.isApplyingTheme = true;
    setTimeout(() => {
      this.themeService.resetToDefault();
      this.customColorInput = this.themeService.getCurrentTheme().primaryColor;
      this.isApplyingTheme = false;
    }, 100);
  }

  // ==========================================================================
  // CUSTOM COLOR METHODS
  // ==========================================================================

  /**
   * Handles custom color input changes
   * @param color - Color input value
   */
  onCustomColorChange(color: string): void {
    this.customColorInput = color;
    this.validateAndPreviewColor(color);
  }

  /**
   * Validates and previews a custom color
   * @param color - Color to validate and preview
   */
  private validateAndPreviewColor(color: string): void {
    // Clear previous validation
    this.colorValidation = null;
    this.colorPreview = {};
    this.showColorPreview = false;

    if (!color || color.length < 4) {
      return;
    }

    try {
      // Validate color
      this.colorValidation = this.themeService.validateColor(color);
      
      // Generate preview if valid
      if (this.colorValidation?.isValid) {
        this.colorPreview = this.themeService.generateColorPreview(color);
        this.showColorPreview = true;
      }
    } catch (error) {
      this.colorValidation = {
        isValid: false,
        warnings: ['Invalid color format']
      };
    }
  }

  /**
   * Applies custom color theme
   */
  onApplyCustomColor(): void {
    if (!this.colorValidation?.isValid) {
      return;
    }

    this.isApplyingTheme = true;
    setTimeout(() => {
      this.themeService.applyCustomTheme(
        this.customColorInput,
        this.customThemeName || 'Custom Theme',
        this.isDarkMode
      );
      this.showCustomColorPanel = false;
      this.isApplyingTheme = false;
    }, 100);
  }

  /**
   * Toggles custom color panel
   */
  onToggleCustomPanel(): void {
    this.showCustomColorPanel = !this.showCustomColorPanel;
    if (this.showCustomColorPanel) {
      this.validateAndPreviewColor(this.customColorInput);
    }
  }

  // ==========================================================================
  // UTILITY METHODS
  // ==========================================================================

  /**
   * Gets display name for theme
   * @param themeName - Theme internal name
   * @returns Human-readable theme name
   */
  getThemeDisplayName(themeName: string): string {
    const displayNames: { [key: string]: string } = {
      'default': 'Material Purple',
      'ocean': 'Ocean Blue',
      'forest': 'Forest Green',
      'sunset': 'Sunset Orange'
    };
    return displayNames[themeName] || themeName;
  }

  /**
   * Gets CSS class for theme preview
   * @param themeName - Theme name
   * @returns CSS class name
   */
  getThemePreviewClass(themeName: string): string {
    return `theme-preview--${themeName}`;
  }

  /**
   * Checks if theme is currently active
   * @param themeName - Theme name to check
   * @returns True if theme is active
   */
  isThemeActive(themeName: string): boolean {
    return this.currentTheme.currentTheme === themeName;
  }

  /**
   * Gets color contrast text color
   * @param backgroundColor - Background color
   * @returns Text color (black or white)
   */
  getContrastTextColor(backgroundColor: string): string {
    // Simple contrast check - in production you might want to use ColorUtils.getContrast
    const hex = backgroundColor.replace('#', '');
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#FFFFFF';
  }
}