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

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

  @Input({ required: true }) url!: string;
  @Input() size: 'auto' | 'cover' | 'contain' | string = 'cover';
  @Input() position = 'center';
  @Input() repeat: 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat' = 'no-repeat';
  @Input() attachment?: 'scroll' | 'fixed' | 'local';
  @Input() opacity = 1;
  @Input() fullScreen = false;
  @Input() zIndex?: number;

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

  ngOnChanges(changes: SimpleChanges): void {
    const relevantChanges = ['url', 'size', 'position', 'repeat', 'attachment', '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.url) {
      return;
    }

    if (this.backgroundId) {
      this.backgroundService.removeBackground(this.backgroundId);
    }

    const config: ImageBackgroundConfig = {
      type: 'image',
      url: this.url,
      size: this.size,
      position: this.position,
      repeat: this.repeat,
      attachment: this.attachment,
      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
      );
    }
  }
}