/* eslint-disable @typescript-eslint/member-ordering */
import { CommonModule } from '@angular/common';
import {
  Component,
  ElementRef,
  effect,
  HostListener,
  inject,
  input,
  OnDestroy,
  output,
  signal,
  viewChild
} from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideMaximize,
  lucideMinimize,
  lucideMonitor,
  lucideVideo,
  lucideVolume2,
  lucideVolumeX
} from '@ng-icons/lucide';

import { UserAvatarComponent } from '../../../../shared';
import { VoiceWorkspacePlaybackService } from '../voice-workspace-playback.service';
import { VoiceWorkspaceStreamItem } from '../voice-workspace.models';

@Component({
  selector: 'app-voice-workspace-stream-tile',
  standalone: true,
  imports: [
    CommonModule,
    NgIcon,
    UserAvatarComponent
  ],
  viewProviders: [
    provideIcons({
      lucideMaximize,
      lucideMinimize,
      lucideMonitor,
      lucideVideo,
      lucideVolume2,
      lucideVolumeX
    })
  ],
  templateUrl: './voice-workspace-stream-tile.component.html',
  host: {
    class: 'block h-full'
  }
})
export class VoiceWorkspaceStreamTileComponent implements OnDestroy {
  private readonly workspacePlayback = inject(VoiceWorkspacePlaybackService);
  private fullscreenHeaderHideTimeoutId: ReturnType<typeof setTimeout> | null = null;

  readonly item = input.required<VoiceWorkspaceStreamItem>();
  readonly focused = input(false);
  readonly featured = input(false);
  readonly compact = input(false);
  readonly mini = input(false);
  readonly immersive = input(false);
  readonly focusRequested = output<string>();
  readonly tileRef = viewChild<ElementRef<HTMLElement>>('tileRoot');
  readonly videoRef = viewChild<ElementRef<HTMLVideoElement>>('streamVideo');

  readonly isFullscreen = signal(false);
  readonly showFullscreenHeader = signal(true);
  readonly volume = signal(100);
  readonly muted = signal(false);

  constructor() {
    effect(() => {
      const ref = this.videoRef();
      const item = this.item();

      if (!ref) {
        return;
      }

      const video = ref.nativeElement;

      if (video.srcObject !== item.stream) {
        video.srcObject = item.stream;
      }

      void video.play().catch(() => {});
    });

    effect(() => {
      this.workspacePlayback.settings();

      const item = this.item();

      if (item.isLocal || !item.hasAudio) {
        this.volume.set(0);
        this.muted.set(false);
        return;
      }

      this.volume.set(this.workspacePlayback.getUserVolume(item.peerKey));
      this.muted.set(this.workspacePlayback.isUserMuted(item.peerKey));
    });

    effect(() => {
      const ref = this.videoRef();
      const item = this.item();
      const muted = this.muted();
      const volume = this.volume();

      if (!ref) {
        return;
      }

      const video = ref.nativeElement;

      if (item.isLocal || !item.hasAudio) {
        video.muted = true;
        video.volume = 0;
        return;
      }

      video.muted = muted;
      video.volume = Math.max(0, Math.min(1, volume / 100));
      void video.play().catch(() => {});
    });

  }

  @HostListener('document:fullscreenchange')
  onFullscreenChange(): void {
    const tile = this.tileRef()?.nativeElement;
    const isFullscreen = !!tile && document.fullscreenElement === tile;

    this.isFullscreen.set(isFullscreen);

    if (isFullscreen) {
      this.revealFullscreenHeader();
      return;
    }

    this.clearFullscreenHeaderHideTimeout();
    this.showFullscreenHeader.set(true);
  }

  ngOnDestroy(): void {
    this.clearFullscreenHeaderHideTimeout();

    const tile = this.tileRef()?.nativeElement;

    if (tile && document.fullscreenElement === tile) {
      void document.exitFullscreen().catch(() => {});
    }
  }

  canToggleFullscreen(): boolean {
    return !this.mini() && !this.compact() && (this.immersive() || this.focused());
  }

  onTilePointerMove(): void {
    if (!this.isFullscreen()) {
      return;
    }

    this.revealFullscreenHeader();
  }

  async onTileDoubleClick(event: MouseEvent): Promise<void> {
    event.preventDefault();
    event.stopPropagation();

    if (!this.canToggleFullscreen()) {
      return;
    }

    const tile = this.tileRef()?.nativeElement;

    if (!tile || !tile.requestFullscreen) {
      return;
    }

    if (document.fullscreenElement === tile) {
      await document.exitFullscreen().catch(() => {});
      return;
    }

    await tile.requestFullscreen().catch(() => {});
  }

  async exitFullscreen(event?: Event): Promise<void> {
    event?.preventDefault();
    event?.stopPropagation();

    if (!this.isFullscreen()) {
      return;
    }

    await document.exitFullscreen().catch(() => {});
  }

  requestFocus(): void {
    this.focusRequested.emit(this.item().id);
  }

  toggleMuted(): void {
    const item = this.item();

    if (item.isLocal || !item.hasAudio) {
      return;
    }

    const nextMuted = !this.muted();

    this.muted.set(nextMuted);
    this.workspacePlayback.setUserMuted(item.peerKey, nextMuted);
  }

  updateVolume(event: Event): void {
    const item = this.item();

    if (item.isLocal || !item.hasAudio) {
      return;
    }

    const input = event.target as HTMLInputElement;
    const nextVolume = Math.max(0, Math.min(100, parseInt(input.value, 10) || 0));

    this.volume.set(nextVolume);
    this.workspacePlayback.setUserVolume(item.peerKey, nextVolume);

    if (nextVolume > 0 && this.muted()) {
      this.muted.set(false);
      this.workspacePlayback.setUserMuted(item.peerKey, false);
    }
  }

  displayName(): string {
    return this.item().isLocal ? 'You' : this.item().user.displayName;
  }

  streamIconName(): string {
    return this.item().kind === 'camera' ? 'lucideVideo' : 'lucideMonitor';
  }

  streamBadgeLabel(): string {
    return this.item().kind === 'camera' ? 'Camera live' : 'Screen share live';
  }

  fullscreenDescription(): string {
    if (this.item().isLocal) {
      return this.item().kind === 'camera'
        ? 'Local camera preview in fullscreen'
        : 'Local preview in fullscreen';
    }

    return this.item().kind === 'camera'
      ? 'Fullscreen camera view'
      : 'Fullscreen stream view';
  }

  localPreviewDescription(): string {
    return this.item().kind === 'camera'
      ? 'Your camera preview never captures audio.'
      : 'Your preview stays muted locally to avoid audio feedback.';
  }

  private scheduleFullscreenHeaderHide(): void {
    this.clearFullscreenHeaderHideTimeout();

    this.fullscreenHeaderHideTimeoutId = setTimeout(() => {
      this.showFullscreenHeader.set(false);
      this.fullscreenHeaderHideTimeoutId = null;
    }, 2200);
  }

  private revealFullscreenHeader(): void {
    this.showFullscreenHeader.set(true);
    this.scheduleFullscreenHeaderHide();
  }

  private clearFullscreenHeaderHideTimeout(): void {
    if (this.fullscreenHeaderHideTimeoutId === null) {
      return;
    }

    clearTimeout(this.fullscreenHeaderHideTimeoutId);
    this.fullscreenHeaderHideTimeoutId = null;
  }
}
