import { Component, computed, inject, OnInit, Signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { Oauth2Service } from './oauth2.service';

@Component({
  selector: 'app-oauth2-callback',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="min-h-screen bg-deep-blue flex items-center justify-center">
      <div class="text-center">
        <h2 class="text-2xl font-bold text-white mb-4">Authentifizierung...</h2>
        <div
          class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-emerald mx-auto"
        ></div>
        <p *ngIf="error()" class="mt-4 text-accent-red">{{ error() }}</p>
      </div>
    </div>
  `,
})
export default class OAuth2CallbackComponent implements OnInit {
  error: Signal<string> = computed(() => this.oauthService.error());

  private route: ActivatedRoute = inject(ActivatedRoute);
  private router: Router = inject(Router);
  private oauthService: Oauth2Service = inject(Oauth2Service);

  ngOnInit(): void {
    this.route.queryParams.subscribe((params) => {
      const code = params['code'];
      const provider = this.route.snapshot.data['provider'] || 'github';

      if (code) {
        this.oauthService.oauth(provider, code);
      } else {
        this.oauthService.error.set(
          'Authentifizierung fehlgeschlagen. Bitte versuchen Sie es erneut.'
        );

        setTimeout(() => {
          this.router.navigate(['/']);
        }, 3000);
      }
    });
  }
}
