import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { Auth } from '../../interface/Auth.interface';
import { lastValueFrom } from 'rxjs';
import { MatDialog } from '@angular/material/dialog';
import { UsersService } from '../../../modules/Administrador/services/users.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {


  public error: string = ""; //mensaje de error
  public status: number = 0; //recibe el status de la petición
  public showPassword: boolean = false; //cambiar visibilidad del campo password
  public isLoading: boolean = false; //mostrar spinner


  public form = new FormGroup({
    idUsuario: new FormControl<string>('', Validators.required),
    contrasenaHash: new FormControl<string>('', Validators.required),
  });

  constructor(private _authService: AuthService,
    private router: Router,
    private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    public dialog: MatDialog) {
    this._MatIconRegister.addSvgIcon('info', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/icons.svg'));
    // var ipAddress = window.location.hostname;
    // console.log(ipAddress);
    // this.logout();
  }

  get loginData(): Auth {
    const data = this.form.value as Auth;
    return data;
  }

  login() {
    this.isLoading = true;
    if (this.form.invalid) {

      return Object.values(this.form.controls).forEach(control => {
        control.markAllAsTouched();
        this.isLoading = false;
      });
    }
    return this._authService.login(this.loginData).subscribe(
      (response: any) => {
        console.log(response);

        this.error = response.message;
        this.status = response.status;
        let token = response.token;
        localStorage.setItem('userData', JSON.stringify(response.data));
        localStorage.setItem('token', token);
        this.isLoading = false;
        switch (response.data[1]) {
          case 'PF':
            this.router.navigate(['/homePadres/registroAlumno']);
            break;
          case 'AD':
            this.router.navigate(['/homeAdmin/main']);
            break;
          case 'AL':
            this.router.navigate(['/homeAlumno/main']);
            break;
          case 'PR':
            this.router.navigate(['/homeProfe/main']);
            break;
        }
        // this.router.navigate(['/homeAdmin/main']);
      }, (err) => {
        console.log(err);
        if (err.error.type === 'MAX_DEVICE') {
          Swal.fire({
            icon: 'error',
            title: `${err.error.errorMessage}`
          })
          this.form.reset;
        } else if (err.error.type === 'C_PASS') {
          Swal.fire({
            icon: 'info',
            title: `${err.error.message}`,
            showCancelButton: false,
            allowEscapeKey: false,
            allowOutsideClick: false,
            confirmButtonColor: '#3085d6',
            confirmButtonText: "Cambiar Contraseña"
          }).then((result: any) => {

            if (result.isConfirmed) {
              localStorage.setItem('id', err.error.userId);
              setTimeout(() => {
                this.router.navigate(['auth/changePassword']);
              }, 200);

            }
          })
        }

        this.isLoading = false;
        this.error = err.error.message;
        this.status = err.error.status;
      })
  }

  toggleVisibility() {
    this.showPassword = !this.showPassword;
  }


  campoNoValido(campo: string): boolean {
    if (this.form.get(campo)?.invalid && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }

  campoVacio(campo: string): boolean {
    if ((this.form.get(campo)?.value === '') && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }


  openDialog() {
    this.dialog.open(ModalEmail, {
      autoFocus: false
    });
  }

}


@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'email.component.html',
  styleUrl: './login.component.css'

})
export class ModalEmail {

  constructor(
    private authService: AuthService
  ) { }

  public form = new FormGroup(
    {
      email: new FormControl<string>('', Validators.email),
    }
  );

  campoNoValido(campo: string): boolean {
    if (this.form.get(campo)?.invalid && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }

  campoVacio(campo: string): boolean {
    if ((this.form.get(campo)?.value === '') && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }

  enviarCorreo() {
    let info = {
      email: this.form.value.email
    }
    return this.authService.sendMail(info).subscribe((response) => {
      console.log(response);
    })
  }

}

