import { DOCUMENT } from '@angular/common';
import {
  AfterViewInit,
  Component,
  ElementRef,
  HostListener,
  OnInit,
  inject,
  input,
  output,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { ScreenShareQuality, SCREEN_SHARE_QUALITY_OPTIONS } from '../../../domains/screen-share';
import { screenShareQualityI18nKey } from '../../../shared-kernel';
import { ModalBackdropComponent } from '../modal-backdrop/modal-backdrop.component';
import { portalHostElementToBody } from '../portal-host-to-body.logic';
import { APP_TRANSLATE_IMPORTS, AppI18nService } from '../../../core/i18n';

@Component({
  selector: 'app-screen-share-quality-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ModalBackdropComponent,
    ...APP_TRANSLATE_IMPORTS
  ],
  templateUrl: './screen-share-quality-dialog.component.html',
  host: {
    style: 'display: contents;'
  }
})
export class ScreenShareQualityDialogComponent implements OnInit, AfterViewInit {
  selectedQuality = input.required<ScreenShareQuality>();
  includeSystemAudio = input(false);

  confirmed = output<ScreenShareQuality>();
  cancelled = output<undefined>();

  readonly qualityOptions = SCREEN_SHARE_QUALITY_OPTIONS;
  readonly activeQuality = signal<ScreenShareQuality>('balanced');

  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly document = inject(DOCUMENT);
  private readonly appI18n = inject(AppI18nService);

  @HostListener('document:keydown.escape')
  onEscape(): void {
    this.cancelled.emit(undefined);
  }

  ngOnInit(): void {
    this.activeQuality.set(this.selectedQuality());
  }

  ngAfterViewInit(): void {
    portalHostElementToBody(this.host.nativeElement, this.document.body);
  }

  chooseQuality(quality: ScreenShareQuality): void {
    this.activeQuality.set(quality);
  }

  confirm(): void {
    this.confirmed.emit(this.activeQuality());
  }

  qualityLabel(quality: ScreenShareQuality): string {
    return this.appI18n.instant(screenShareQualityI18nKey(quality, 'label'));
  }

  qualityDescription(quality: ScreenShareQuality): string {
    return this.appI18n.instant(screenShareQualityI18nKey(quality, 'description'));
  }
}
