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;
  @ViewChild('videoRef', { static: true }) videoElement!: ElementRef<HTMLIFrameElement>;

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

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

    this.initializePlayer()


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


  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;

    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];

        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()
  }

  
}
