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 { ScoreTableComponent } from '../../score-table/score-table/score-table.component';
import {Firestore, getDocs, where} from "@angular/fire/firestore";
import {collection, query} from "firebase/firestore";
import { HeaderLoginSignupResetpw } from '../../shared/header-login-signup-resetpw/header-lsr.component'

@Component({
  selector: 'app-login-password',
  standalone: true,
  providers: [AuthService],
  templateUrl: './resetPw.component.html',
  styleUrl: './resetPw.component.css',
  imports: [
    CommonModule,
    AngularMaterialModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    HttpClientModule,
    LoadingSpinnerComponent,
    ScoreTableComponent,
    HeaderLoginSignupResetpw,
  ],
})

export class ResetPwComponent implements OnInit {
  /** Represents the login form group */
  loginForm!: FormGroup;
  isLoading = false;
  isAuthenticated = false;

  constructor(
    private authService: AuthService,
    private notifierService: NotifierService,
    private router: Router,
    private firestore: Firestore,
  ) {}

  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(/^[a-zA-Z0-9._%+-]+\.+[a-zA-Z0-9._%+-]+@(eviden\.com|atos\.net)$/),
      ]),
    });
  }

  onSubmit() {
    const email = this.loginForm.get('email')?.value;
    const lowercaseEmail = email.toLowerCase();
    this.isLoading = true;
    const usersCollection = collection(this.firestore, 'users');
    const scoreQuery = query(usersCollection, where('email', '==', lowercaseEmail));

    getDocs(scoreQuery)
        .then(querySnapshot => {
          if (querySnapshot.size > 0) {
            // Email exists, perform desired action
            this.authService.resetPassword(email).then(() => {
                this.router.navigate(['/login']);
                this.isLoading = false;
                this.notifierService.showNotification("Reset Link gesendet an "+email.toLowerCase(), 'OK');
              }
            );

          } else {
            this.notifierService.showNotification("Fehler: Die E-Mail existiert nicht!", 'OK');
            this.isLoading = false;
          }
        });

    this.loginForm.reset();
  }
}