import {Component, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {Title} from '@angular/platform-browser';
import {ALTITUDE_VERSION} from '@custom-types/constant';
import {ScrollService} from '@services/scroll.service';
import {CommonModule, NgOptimizedImage} from '@angular/common';
import {HeaderComponent} from '@header/header.component';
import {CopyIpComponent} from '@shared-components/copy-ip/copy-ip.component';
import {RouterLink} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {interval, map} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {startWith} from 'rxjs/operators';

interface MinecraftServerStatus {
  online?: boolean;
  players?: {
    online?: number;
  };
}

@Component({
  standalone: true,
  imports: [
    CommonModule,
    HeaderComponent,
    CopyIpComponent,
    RouterLink,
    NgOptimizedImage
  ],
  providers: [
    {provide: JwtHelperService, useFactory: () => new JwtHelperService()}
  ],
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrl: './home.component.scss'
})
export class HomeComponent implements OnInit, OnDestroy {
  private httpClient = inject(HttpClient);
  private titleService = inject(Title);
  public scrollService = inject(ScrollService);
  public playerCount = signal<null | number>(null);
  private playerCountUpdateInterval = interval(60000).pipe(
    startWith(() => 0),
  ).subscribe(() => {
    this.updatePlayerCount();
  });

  private slides: string[] = ["/public/img/backgrounds/caruselimage2.png",
    "/public/img/backgrounds/caruselimage4.png",
    "/public/img/backgrounds/caruselimage1.png",
    "/public/img/backgrounds/caruselimage5.png",
    "/public/img/backgrounds/caruselimage3.png"
  ];

  private slideIndex = 0;
  public carouselOpacity = 1;
  public triggerAnimation = false;

  ngOnInit(): void {
    this.titleService.setTitle('Survival Minecraft Server on ' + ALTITUDE_VERSION + ' | Altitude Community');
    this.randomizeSlides()
  }

  ngOnDestroy(): void {
    this.playerCountUpdateInterval.unsubscribe();
  }

  private randomizeSlides(): void {
    const array = [...this.slides];

    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }

    this.slides = array;
  }

  get slide(): string {
    return this.slides[this.slideIndex];
  }

  public previousSlide(): void {
    if (this.slideIndex > 0) {
      this.setSlide(this.slideIndex - 1);
    } else {
      this.setSlide(this.slides.length - 1);
    }
  }

  public nextSlide(): void {
    this.setSlide((this.slideIndex + 1) % this.slides.length);
  }

  public getSlideIndices(): number[] {
    return Array.from({length: this.slides.length}, (_, i) => i);
  }

  public setSlide(slide: number): void {
    this.slideIndex = slide;
    this.triggerAnimation = true
    this.carouselOpacity = 0;

    const startTime = Date.now();
    const duration = 1500;

    const animate = () => {
      const elapsed = Date.now() - startTime;

      this.carouselOpacity = Math.min(elapsed / duration, 1);

      if (this.carouselOpacity < 1) {
        requestAnimationFrame(animate);
      }
    };
    requestAnimationFrame(animate);
  }

  public getDotClass(slide: number): string {
    return slide == this.slideIndex ? 'active-dot' : 'inactive-dot';
  }

  public scrollToSection(): void {
    const element = document.getElementById('scrollingpoint');
    if (element) {
      element.scrollIntoView({behavior: 'smooth', block: 'start'});
    } else {
      console.error('Element with id "scrollingpoint" not found.');
    }
  }

  private updatePlayerCount() {
    this.httpClient.get<MinecraftServerStatus>('https://api.mcsrvstat.us/2/play.alttd.com').pipe(
      map(response => {
        if (response.online && response.players && response.players.online) {
          this.playerCount.set(response.players.online);
        }
      })
    ).subscribe();
  }

  protected readonly ALTITUDE_VERSION = ALTITUDE_VERSION;
}
