import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { BrandColors, ThemePreview } from '../../../../../hcl-studio/src/lib/models/hcl.models';
import { HCLStudioService } from '../../../../../hcl-studio/src/lib/hcl-studio.service';
import { HCLConverter } from '../../../../../hcl-studio/src/lib/core/hcl-converter';
import { DEFAULT_THEMES } from '../../../../../hcl-studio/src/lib/themes/theme-presets';



@Component({
  selector: 'app-hcl-studio-demo',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="hcl-studio-demo">
      <div class="demo-header">
        <h1>HCL Studio Demo</h1>
        <p>Dynamic theme switching using HCL color space</p>
      </div>

      <!-- Current Theme Info -->
      <div class="current-theme-info" *ngIf="currentTheme">
        <h3>Current Theme: {{ currentTheme.name }}</h3>
        <div class="color-swatches">
          <div class="swatch" [style.background]="currentTheme.primary">
            <span>Primary</span>
          </div>
          <div class="swatch" [style.background]="currentTheme.secondary">
            <span>Secondary</span>
          </div>
          <div class="swatch" [style.background]="currentTheme.tertiary">
            <span>Tertiary</span>
          </div>
        </div>
      </div>

      <!-- Mode Toggle -->
      <div class="mode-controls">
        <button 
          class="mode-toggle-btn"
          (click)="toggleMode()"
          [class.dark]="isDarkMode"
        >
          {{ isDarkMode ? 'Switch to Light' : 'Switch to Dark' }}
        </button>
      </div>

      <!-- Built-in Themes -->
      <div class="themes-section">
        <h3>Built-in Themes</h3>
        <div class="theme-grid">
          <div 
            *ngFor="let theme of availableThemes" 
            class="theme-card"
            [class.active]="theme.id === currentTheme?.id"
            (click)="switchTheme(theme.id)"
          >
            <div class="theme-preview">
              <div class="color-strip" [style.background]="theme.primary"></div>
              <div class="color-strip" [style.background]="theme.secondary"></div>
              <div class="color-strip" [style.background]="theme.tertiary"></div>
            </div>
            <span class="theme-name">{{ theme.name }}</span>
          </div>
        </div>
      </div>

      <!-- Custom Color Input -->
      <div class="custom-theme-section">
        <h3>Create Custom Theme</h3>
        <div class="custom-inputs">
          <div class="color-input-group">
            <label>Primary Color:</label>
            <input 
              type="color" 
              [(ngModel)]="customColors.primary" 
              (change)="previewCustomTheme()"
            >
            <input 
              type="text" 
              [(ngModel)]="customColors.primary" 
              (input)="previewCustomTheme()"
              placeholder="#6750A4"
            >
          </div>
          
          <div class="color-input-group">
            <label>Secondary Color:</label>
            <input 
              type="color" 
              [(ngModel)]="customColors.secondary" 
              (change)="previewCustomTheme()"
            >
            <input 
              type="text" 
              [(ngModel)]="customColors.secondary" 
              (input)="previewCustomTheme()"
              placeholder="#625B71"
            >
          </div>

          <div class="color-input-group">
            <label>Tertiary Color:</label>
            <input 
              type="color" 
              [(ngModel)]="customColors.tertiary" 
              (change)="previewCustomTheme()"
            >
            <input 
              type="text" 
              [(ngModel)]="customColors.tertiary" 
              (input)="previewCustomTheme()"
              placeholder="#7D5260"
            >
          </div>
        </div>

        <div class="custom-actions">
          <button class="preview-btn" (click)="previewCustomTheme()">
            Preview Theme
          </button>
          <button class="apply-btn" (click)="applyCustomTheme()">
            Apply Theme
          </button>
        </div>

        <!-- Color Preview -->
        <div *ngIf="colorPreview" class="color-preview">
          <h4>Generated Palette Preview</h4>
          <div class="preview-swatches">
            <div 
              *ngFor="let color of colorPreview | keyvalue" 
              class="preview-swatch"
              [style.background]="color.value"
              [style.color]="getContrastColor(color.value)"
            >
              {{ color.key }}
            </div>
          </div>
        </div>
      </div>

      <!-- Demo Components -->
      <div class="demo-components">
        <h3>Theme Demo Components</h3>
        
        <div class="component-showcase">
          <!-- Buttons -->
          <div class="showcase-section">
            <h4>Buttons</h4>
            <div class="button-group">
              <button class="btn-primary">Primary Button</button>
              <button class="btn-secondary">Secondary Button</button>
              <button class="btn-tertiary">Tertiary Button</button>
            </div>
          </div>

          <!-- Cards -->
          <div class="showcase-section">
            <h4>Cards</h4>
            <div class="card-group">
              <div class="demo-card primary">
                <h5>Primary Card</h5>
                <p>This card uses primary colors</p>
              </div>
              <div class="demo-card secondary">
                <h5>Secondary Card</h5>
                <p>This card uses secondary colors</p>
              </div>
            </div>
          </div>

          <!-- Surfaces -->
          <div class="showcase-section">
            <h4>Surface Variations</h4>
            <div class="surface-group">
              <div class="demo-surface surface-low">Surface Low</div>
              <div class="demo-surface surface-container">Surface Container</div>
              <div class="demo-surface surface-high">Surface High</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styleUrls: ['./hcl-studio-demo.component.scss']
})
export class HclStudioDemoComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  // State
  availableThemes: ThemePreview[] = [];
  currentTheme: ThemePreview | null = null;
  isDarkMode = false;

  // Custom theme inputs
  customColors: BrandColors = {
    primary: '#6750A4',
    secondary: '#625B71',
    tertiary: '#7D5260'
  };

  colorPreview: { [key: string]: string } | null = null;

  constructor(private hclStudio: HCLStudioService) {}

  ngOnInit(): void {
    // Initialize HCL Studio with default themes
    this.hclStudio.initialize({
      themes: DEFAULT_THEMES,
      defaultTheme: 'material-purple',
      autoMode: false
    });

    // Subscribe to theme changes
    this.hclStudio.themeState$
      .pipe(takeUntil(this.destroy$))
      .subscribe((state: any) => {
        this.availableThemes = state.availableThemes;
        if (state.currentTheme) {
          this.currentTheme = {
            id: state.currentTheme.config.id,
            name: state.currentTheme.config.name,
            description: state.currentTheme.config.description,
            primary: state.currentTheme.config.colors.primary,
            secondary: state.currentTheme.config.colors.secondary,
            tertiary: state.currentTheme.config.colors.tertiary
          };
        }
      });

    // Subscribe to mode changes
    this.hclStudio.currentMode$
      .pipe(takeUntil(this.destroy$))
      .subscribe((mode: string) => {
        this.isDarkMode = mode === 'dark';
      });
  }

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

  switchTheme(themeId: string): void {
    this.hclStudio.switchTheme(themeId);
  }

  toggleMode(): void {
    this.hclStudio.toggleMode();
  }

  previewCustomTheme(): void {
    try {
      this.colorPreview = this.hclStudio.generateColorPreview(this.customColors);
    } catch (error) {
      console.warn('Failed to generate color preview:', error);
      this.colorPreview = null;
    }
  }

  applyCustomTheme(): void {
    const customTheme = this.hclStudio.createCustomTheme(
      'custom-theme',
      'My Custom Theme',
      this.customColors,
      'User-created custom theme'
    );

    this.hclStudio.switchTheme('custom-theme');
  }

  getContrastColor(backgroundColor: string): string {
    try {
      const ratio1 = HCLConverter.getContrastRatio(backgroundColor, '#000000');
      const ratio2 = HCLConverter.getContrastRatio(backgroundColor, '#FFFFFF');
      return ratio1 > ratio2 ? '#000000' : '#FFFFFF';
    } catch {
      return '#000000';
    }
  }
}