import { Component, EventEmitter, Output, signal, inject } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginRequest } from '../../../model/auth/LoginRequest';
import { AuthService } from '@service/auth.service';
import { CommonModule } from '@angular/common';
import { environment } from '@environments/environment';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './login.component.html',
})
export class LoginComponent {
  loginForm: FormGroup;
  errorMessage = signal('');
  isLoading = signal(false);
  @Output() switchForm = new EventEmitter<void>();
  @Output() closeDialog = new EventEmitter<void>();
  @Output() forgotPassword = new EventEmitter<void>();

  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private router = inject(Router);

  constructor() {
    this.loginForm = this.fb.group({
      usernameOrEmail: ['', [Validators.required]],
      password: ['', [Validators.required]],
    });
  }

  get form() {
    return this.loginForm.controls;
  }

  switchToRegister(): void {
    this.switchForm.emit();
  }

  onSubmit(): void {
    if (this.loginForm.invalid) {
      return;
    }

    this.isLoading.set(true);
    this.errorMessage.set('');

    const loginRequest: LoginRequest = {
      usernameOrEmail: this.form['usernameOrEmail'].value,
      password: this.form['password'].value,
    };

    this.authService.login(loginRequest).subscribe({
      next: () => {
        this.closeDialog.emit();
        this.router.navigate(['/home']);
      },
      error: (err) => {
        this.isLoading.set(false);
        this.errorMessage.set(
          err.error?.message || 'Failed to login. Please check your credentials.'
        );
      },
    });
  }

  loginWithGithub(): void {
    this.isLoading.set(true);
    window.location.href = `${environment.apiUrl}/oauth2/github/authorize`;
  }

  loginWithGoogle(): void {
    this.isLoading.set(true);
    window.location.href = `${environment.apiUrl}/oauth2/google/authorize`;
  }

  switchToForgotPassword() {
    this.forgotPassword.emit();
  }
}
