import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { finalize } from 'rxjs';
import { getErrorMessage } from '../../core/http/error-message.util';
import { GameApiService } from '../../services/game-api.service';

@Component({
  selector: 'app-welcome',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './welcome.component.html',
  styleUrl: './welcome.component.css'
})
export class WelcomeComponent {
  creating = false;
  errorMessage = '';
  showDifficultySelector = false;
  showJoinGameForm = false;
  gameIdInput = '';
  joiningGame = false;

  constructor(
    private readonly router: Router,
    private readonly gameApi: GameApiService
  ) {}

  startOneVsOne(): void {
    if (this.creating) {
      return;
    }

    this.errorMessage = '';
    this.creating = true;

    this.gameApi
      .createGame()
      .pipe(finalize(() => (this.creating = false)))
      .subscribe({
        next: (game) => {
          void this.router.navigate(['/game', game.gameId]);
        },
        error: (error) => {
          this.errorMessage = getErrorMessage(error, 'Unable to create a game.');
        }
      });
  }

  startVsBot(difficulty: 'easy' | 'medium' | 'hard'): void {
    if (this.creating) {
      return;
    }

    this.errorMessage = '';
    this.creating = true;
    this.showDifficultySelector = false;

    this.gameApi
      .createGameVsBot(difficulty)
      .pipe(finalize(() => (this.creating = false)))
      .subscribe({
        next: (game) => {
          void this.router.navigate(['/game', game.gameId]);
        },
        error: (error) => {
          this.errorMessage = getErrorMessage(error, 'Unable to create a game against bot.');
        }
      });
  }

  toggleDifficultySelector(): void {
    this.showDifficultySelector = !this.showDifficultySelector;
    this.showJoinGameForm = false;
    this.errorMessage = '';
  }

  toggleJoinGameForm(): void {
    this.showJoinGameForm = !this.showJoinGameForm;
    this.showDifficultySelector = false;
    this.errorMessage = '';
    this.gameIdInput = '';
  }

  joinGame(): void {
    if (this.joiningGame || !this.gameIdInput.trim()) {
      return;
    }

    this.errorMessage = '';
    this.joiningGame = true;

    this.gameApi
      .getGame(this.gameIdInput.trim())
      .pipe(finalize(() => (this.joiningGame = false)))
      .subscribe({
        next: (game) => {
          void this.router.navigate(['/game', game.gameId]);
        },
        error: (error) => {
          this.errorMessage = getErrorMessage(error, 'Unable to find or join the game.');
        }
      });
  }

  clearJoinGameForm(): void {
    this.showJoinGameForm = false;
    this.gameIdInput = '';
    this.errorMessage = '';
  }
}
