import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { AppService } from 'src/app/shared/services/app.service';
import { IAppConfig } from 'src/app/shared/models/app-config.model';
import { OAuthService } from 'angular-oauth2-oidc';
import { AuthService } from 'src/app/shared/services/auth.service';
import { GeneralMetricsApiService } from '../openApis/openSliceMetrics/services';
import { asyncScheduler, forkJoin, scheduled } from 'rxjs';
import { catchError } from 'rxjs/operators';
import Player from '@vimeo/player';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit {

  constructor(
    private appService: AppService,
    public authService: AuthService,
    private generalMetricsService: GeneralMetricsApiService
  ) { }

  config: IAppConfig
  loggedIn: boolean
  // Video section variables
  private player: Player;
  videoLoaded: boolean = false;
  isLoading: boolean = true;

  @ViewChild('videoRef', { static: true }) videoElement!: ElementRef<HTMLIFrameElement>;

  // Metrics section variables
  animatedCounts = {
    registeredUsers: NaN,
    publishedServiceSpecs: NaN,
    registeredResourceSpecs: NaN
  };
  targetCounts = {
    registeredUsers: NaN,
    publishedServiceSpecs: NaN,
    registeredResourceSpecs: NaN
  };
  private intervalId: any;

  ngOnInit() {
    this.config = this.appService.config
    this.authService.isAuthenticated$.subscribe(
      isAuthenticated => this.loggedIn = isAuthenticated
    )

    this.initializePlayer()


    forkJoin({
      registeredUsers: this.generalMetricsService.getRegisteredIndividuals().pipe(
        catchError(error => {
          console.error('Failed to load registered users', error);
          return scheduled([{ registeredIndividuals: NaN }], asyncScheduler);
        })
      ),
      publishedServiceSpecs: this.generalMetricsService.getPublishedServiceSpecifications().pipe(
        catchError(error => {
          console.error('Failed to load published specs', error);
          return scheduled([{ publishedServiceSpecifications: NaN }], asyncScheduler);
        })
      ),
      registeredResourceSpecs: this.generalMetricsService.getRegisteredResourceSpecifications().pipe(
        catchError(error => {
          console.error('Failed to load resource specs', error);
          return scheduled([{ registeredResourceSpecifications: NaN }], asyncScheduler);
        })
      )
    })
      // .pipe(delay(500))
      .subscribe(
        results => {

          this.targetCounts.registeredUsers = results.registeredUsers.registeredIndividuals;
          this.targetCounts.publishedServiceSpecs = results.publishedServiceSpecs.publishedServiceSpecifications;
          this.targetCounts.registeredResourceSpecs = results.registeredResourceSpecs.registeredResourceSpecifications;
          this.isLoading = false;
          // Initialize animated counts
          this.startAnimation();

        }
      );
  }

  isNaN(value: any): boolean {
    return isNaN(value);
  }

  initializePlayer() {
    this.player = new Player(this.videoElement.nativeElement, {
      url: "https://vimeo.com/1096581653/5fb6b3ded9",
      loop: true,
      autoplay: true,
      controls: true,
      muted: true,
      playsinline: true, // For mobile devices
    });

    this.player.ready().then(() => {
      this.player.on('play', () => {
        this.videoLoaded = true;
      });

    }).catch((error: any) => {
      console.error('Player readiness error:', error);
    });
  }

  // async togglePlay() {
  //   if (!this.player) {
  //     console.error('Player not initialized');
  //     return;
  //   }
  
  //   try {
  //     if (this.isPlaying) {
  //       await this.player.pause();
  //     } else {
  //       await this.player.play();
  //     }
  //   } catch (error) {
  //     console.error('Playback error:', error);
  //   }
  // }

  // async seekVideo(time: number) {
  //   if (!this.player) return;
  //   try {
  //     await this.player.setCurrentTime(parseFloat(time.toString()));
  //   } catch (error) {
  //     console.error('Seek error:', error);
  //   }
  // }

  // formatTime(seconds: number): string {
  //   if (isNaN(seconds)) return '0:00';
  //   const minutes = Math.floor(seconds / 60);
  //   const remainingSeconds = Math.floor(seconds % 60);
  //   return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
  // }

  // toggleFullscreen() {
  //   const elem = this.videoElement.nativeElement.parentElement;
  
  //   if (!document.fullscreenElement) {
  //     if (elem?.requestFullscreen) {
  //       elem.requestFullscreen();
  //     } else if ((elem as any)?.webkitRequestFullscreen) { /* Safari */
  //       (elem as any).webkitRequestFullscreen();
  //     } else if ((elem as any)?.msRequestFullscreen) { /* IE */
  //       (elem as any).msRequestFullscreen();
  //     }
  //   } else {
  //     if (document.exitFullscreen) {
  //       document.exitFullscreen();
  //     }
  //   }
  // }

  startAnimation() {
    const stepTime = 50;

    // Initialize counts to NaN if the target is NaN (api didn't respond), otherwise start from 0 and animate the count
    this.animatedCounts = {
      registeredUsers: isNaN(this.targetCounts.registeredUsers) ? NaN : 0,
      publishedServiceSpecs: isNaN(this.targetCounts.publishedServiceSpecs) ? NaN : 0,
      registeredResourceSpecs: isNaN(this.targetCounts.registeredResourceSpecs) ? NaN : 0
    };

    this.intervalId = setInterval(() => {
      for (const key in this.animatedCounts) {
        const k = key as keyof typeof this.animatedCounts;
        const current = this.animatedCounts[k];
        const target = this.targetCounts[k];

        if (isNaN(target)) {
          this.animatedCounts[k] = NaN;
          continue;
        }

        const delta = target - current;

        if (Math.abs(delta) > 0) {
          this.animatedCounts[k] += Math.ceil(delta / 5);
        }
      }
    }, stepTime);

  }

  ngOnDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

  login() {
    this.authService.login()
  }


}
