import { Component, Input, OnInit, OnDestroy, OnChanges, SimpleChanges, ElementRef, inject, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { PatternConfig, PatternType } from '../../types/background.types';
import { BackgroundService } from '../../services/background.service';

@Component({
  selector: 'ui-pattern-background',
  standalone: true,
  template: '<ng-content></ng-content>',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  host: {
    'class': 'ui-background ui-background--pattern'
  }
})
export class PatternBackgroundComponent implements OnInit, OnDestroy, OnChanges {
  private readonly elementRef = inject(ElementRef<HTMLElement>);
  private readonly backgroundService = inject(BackgroundService);
  private backgroundId?: string;

  @Input() pattern: PatternType = 'dots';
  @Input() primaryColor = '#000000';
  @Input() secondaryColor = '#ffffff';
  @Input() size: string | number = 20;
  @Input() opacity = 1;
  @Input() fullScreen = false;
  @Input() zIndex?: number;

  ngOnInit(): void {
    this.applyBackground();
  }

  ngOnChanges(changes: SimpleChanges): void {
    const relevantChanges = ['pattern', 'primaryColor', 'secondaryColor', 'size', 'opacity', 'fullScreen', 'zIndex'];
    if (relevantChanges.some(key => changes[key])) {
      this.applyBackground();
    }
  }

  ngOnDestroy(): void {
    if (this.backgroundId) {
      this.backgroundService.removeBackground(this.backgroundId);
    }
  }

  private applyBackground(): void {
    if (this.backgroundId) {
      this.backgroundService.removeBackground(this.backgroundId);
    }

    const config: PatternConfig = {
      type: 'pattern',
      pattern: this.pattern,
      primaryColor: this.primaryColor,
      secondaryColor: this.secondaryColor,
      size: this.size,
      opacity: this.opacity
    };

    if (this.fullScreen) {
      this.backgroundId = this.backgroundService.applyFullScreenBackground(config, {
        zIndex: this.zIndex || -1
      });
    } else {
      this.backgroundId = this.backgroundService.applyBackground(
        this.elementRef.nativeElement,
        config
      );
    }

    // Update host class
    this.elementRef.nativeElement.classList.add(`ui-background--pattern-${this.pattern}`);
  }
}