import { Component } from '@angular/core';
import { AngularMaterialModule } from '../../angular-material/angular-material.module';
import {
  FormControl,
  Validators,
  FormsModule,
  ReactiveFormsModule,
  FormGroup,
} from '@angular/forms';
import { ActivatedRoute, 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 { 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';
import { MatDialog } from '@angular/material/dialog';
import { CustomDialogComponent } from '../../shared/custom-dialog/custom-dialog.component';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    CommonModule,
    AngularMaterialModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    HttpClientModule,
    LoadingSpinnerComponent,
    ScoreTableComponent,
    HeaderLoginSignupResetpw,
  ],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css',
})
export class LoginComponent {
  loginForm!: FormGroup;
  isLoading = false;
  isAuthenticated = false;
  hide = true;
  qrData: { score: string; uid: string } | null = null;

  constructor(
    private authService: AuthService,
    private router: Router,
    private pendingActionsService: PendingActionsService,
    private dialog: MatDialog,
    private route: ActivatedRoute
  ) {}

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

    this.loginForm = new FormGroup({
      email: new FormControl('', [
        Validators.required,
        Validators.email,
        Validators.pattern(/\b[A-Za-z0-9._%+-]+@(atos\.net|eviden\.com)\b/),
      ]),
    });
    this.route.queryParams.subscribe((params) => {
      this.qrData = { score: params['score'], uid: params['uid'] };
    });
  }

  async onSubmit() {
    const email = this.loginForm.get('email')?.value;
    this.isLoading = true;
    console.log('login qrData=', this.qrData);

    this.authService.signUp(email, this.qrData?.score, this.qrData?.uid);
    this.dialog.open(CustomDialogComponent, {
      data: {
        title: 'E-Mail-Anmeldung',
        bodyText:
          'Eine Anmeldungs-Email wurde an deine Adresse gesendet. Bitte überprüfe dein Postfach und klicke auf den Link, um dich anzumelden.',
      },
    });
    this.isLoading = false;
    // Handle the pending score after successful login

    this.loginForm.reset();
  }
}
