import { Component, OnInit } from '@angular/core';
import { AngularMaterialModule } from '../../angular-material/angular-material.module';
import {
  FormControl,
  Validators,
  FormsModule,
  ReactiveFormsModule,
  FormGroup,
} from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { AuthService } from '../authService/auth.service';
import { HttpClientModule } from '@angular/common/http';
import { LoadingSpinnerComponent } from '../../shared/loading-spinner/loading-spinner.component';
import { NotifierService } from '../../shared/notifierService/notifier.service';
import { PendingActionsService } from '../../score/pending-actions.service';
import { ScoreTableComponent } from '../../score-table/score-table/score-table.component';
import { HeaderLoginSignupResetpw } from '../../shared/header-login-signup-resetpw/header-lsr.component';

/**
 * LoginComponent represents the component responsible for handling the login functionality.
 * It allows users to enter their email and password to authenticate themselves.
 * This component utilizes Angular reactive forms for validation and form control management.
 */

@Component({
  selector: 'app-login-password',
  standalone: true,
  providers: [AuthService],
  templateUrl: './login-password.component.html',
  styleUrl: './login-password.component.css',
  imports: [
    CommonModule,
    AngularMaterialModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    HttpClientModule,
    LoadingSpinnerComponent,
    ScoreTableComponent,
    HeaderLoginSignupResetpw,
  ],
})
export class LoginPasswordComponent implements OnInit {
  loginForm!: FormGroup;
  isLoading = false;
  isAuthenticated = false;
  hide = true;

  constructor(
    private authService: AuthService,
    private notifierService: NotifierService,
    private router: Router,
    private pendingActionsService: PendingActionsService
  ) {}

  ngOnInit() {
    this.authService.currentUser$.subscribe((user) => {
      this.isAuthenticated = !!user;
    });

    // Initialize the login form with form controls and validators
    this.loginForm = new FormGroup({
      email: new FormControl('', [
        Validators.required,
        Validators.email,
        Validators.pattern(/\b[A-Za-z0-9._%+-]+@(atos\.net|eviden\.com)\b/),
      ]),
      password: new FormControl('', [
        Validators.required,
        //Validation Text fehlt + blockiert LogIn nach PasswortReset mit einfachem Passwort
        //Validators.minLength(10),
        //Validators.maxLength(20),
      ]),
    });
  }

  onSubmit() {
    const email = this.loginForm.get('email')?.value;
    const password = this.loginForm.get('password')?.value;

    this.isLoading = true;

    this.authService.login(email, password).subscribe(
      async (resData) => {
        this.isLoading = false;
        // Handle the pending score after successful login
        const pendingData = await this.pendingActionsService.getTempQRCodeData(
          this.pendingActionsService.getTempQRId()
        );
        if (pendingData) {
          this.router.navigate(['/user-profile'], {
            queryParams: {
              score: pendingData['score'],
              uid: pendingData['uid'],
            },
          });
        } else {
          this.router.navigate(['/score-table']);
        }
      },
      (errorMessage) => {
        this.notifierService.showNotification(errorMessage, 'OK');
        this.isLoading = false;
      }
    );

    this.loginForm.reset();
  }
}
