import { Component } from '@angular/core';

import { MatchesService } from '@services/matches/matches.service';
import { Matches, MatchState } from '@interfaces/matches';

import { PlayerService } from '@services/player/player.service';
import { Player } from '@interfaces/player';

import { RefereeService } from '@services/referee/referee.service';
import { Referee, RefereeLevel } from '@interfaces/referee';

@Component({
  selector: 'app-home',
  standalone: false,
  templateUrl: './home.component.html',
  styleUrl: './home.component.css',
})
export class HomeComponent {
  latestMatch?: Matches;
  player1?: Player;
  player2?: Player;
  referee?: Referee;
  MatchState = MatchState;
  intervalId?: any;
  timeUntilMatch: string | null = null;

  constructor(
    private matchesService: MatchesService,
    private playerService: PlayerService,
    private refereeService: RefereeService
  ) {}

  ngOnInit(): void {
    this.getLatestMatch();
  }

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

  private getLatestMatch(): void {
    this.matchesService.getMatches().subscribe((matches) => {
      if (matches.length > 0) {
        this.latestMatch = matches[matches.length - 1];
        console.log(
          '[HomeComponent] 🏁 Dernier match ajouté :',
          this.latestMatch
        );

        // Récupération des données liées
        this.loadRelatedEntities(this.latestMatch);

        if (this.latestMatch.state === MatchState.NOT_STARTED) {
          this.updateTimeUntilMatch(); // initial
          this.intervalId = setInterval(() => {
            this.updateTimeUntilMatch();
          }, 60000); // chaque minute
        }
      } else {
        console.warn('[HomeComponent] Aucun match disponible');
      }
    });
  }

  private updateTimeUntilMatch(): void {
    if (!this.latestMatch) return;

    const now = new Date();
    const matchDate = new Date(this.latestMatch.date);
    const diffMs = matchDate.getTime() - now.getTime();

    if (diffMs <= 0) {
      this.timeUntilMatch = null;
      clearInterval(this.intervalId);
      return;
    }

    const totalMinutes = Math.floor(diffMs / (1000 * 60));
    const days = Math.floor(totalMinutes / (60 * 24));
    const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
    const minutes = totalMinutes % 60;

    let result = '';
    if (days > 0) result += `${days}j `;
    if (hours > 0 || days > 0) result += `${hours}h `;
    result += `${minutes}min`;

    this.timeUntilMatch = result.trim();
  }

  private loadRelatedEntities(match: Matches): void {
    this.playerService.getPlayerById(match.player1ID).subscribe((p1) => {
      this.player1 = p1!;
    });

    this.playerService.getPlayerById(match.player2ID).subscribe((p2) => {
      this.player2 = p2!;
    });

    this.refereeService.getRefereeById(match.refereeID).subscribe((ref) => {
      this.referee = ref!;
    });
  }

  getMatchStateLabel(state: MatchState): string {
    switch (state) {
      case MatchState.NOT_STARTED:
        return 'À venir';
      case MatchState.ONGOING:
        return 'En cours';
      case MatchState.OVER:
        return 'Terminé';
      default:
        return 'Inconnu';
    }
  }

  getMatchStateColor(state: MatchState): string {
    switch (state) {
      case MatchState.NOT_STARTED:
        return 'secondary';
      case MatchState.ONGOING:
        return 'warning';
      case MatchState.OVER:
        return 'success';
      default:
        return 'light';
    }
  }

  getTimeUntilMatch(): string | null {
    if (
      !this.latestMatch ||
      this.latestMatch.state !== MatchState.NOT_STARTED
    ) {
      return null;
    }

    const now = new Date();
    const matchDate = new Date(this.latestMatch.date);
    const diffMs = matchDate.getTime() - now.getTime();

    if (diffMs <= 0) return null;

    const totalMinutes = Math.floor(diffMs / (1000 * 60));
    const days = Math.floor(totalMinutes / (60 * 24));
    const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
    const minutes = totalMinutes % 60;

    let result = '';
    if (days > 0) result += `${days}j `;
    if (hours > 0 || days > 0) result += `${hours}h `;
    result += `${minutes}min`;

    return result.trim();
  }
}
