import { Component } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, 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 { UsersService } from '../../../modules/Administrador/services/users.service';


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


  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 showPassword1: boolean = false; //cambiar visibilidad del campo password
  public isLoading: boolean = false; //mostrar spinner


  public matchingPasswords: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
    const formGroup = control as FormGroup;
    const contrasena1 = formGroup.get('contrasena1')?.value;
    const contrasena2 = formGroup.get('contrasena2')?.value;

    // Si las contraseñas no coinciden, retorna un objeto de error
    return contrasena1 === contrasena2 ? null : { noMatch: true };
  }

  // Definir el formulario con el validador personalizado
  public form: FormGroup = new FormGroup(
    {
      contrasena1: new FormControl<string>('', [Validators.required,Validators.pattern(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?!.* ).{8,16}$/)]),
      contrasena2: new FormControl<string>('', Validators.required),
    },
    { validators: this.matchingPasswords }
  );

  // Método para verificar si las contraseñas no coinciden
  public contrasIguales(): boolean {
    return this.form.hasError('noMatch');
  }

  constructor(private _authService: AuthService,
    private router: Router,
    private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private userService: UsersService
  ) {
    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;
  }

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

      return Object.values(this.form.controls).forEach(control => {
        control.markAllAsTouched();
        this.isLoading = false;
      });
    }
    const info = {
      idUsuario: localStorage.getItem('id'),
      contrasenaHash: this.form.get('contrasena1')?.value
    };

    this.userService.changePassword(info).subscribe((response: any) => {
      console.log(response);
      Swal.fire({
        icon: 'success',
        title: `${response.message}`,
        text: 'Debes iniciar sesión, se te reedirigirá a la pantalla de Login',
        showCancelButton: false,
        allowEscapeKey: false,
        allowOutsideClick: false,
        confirmButtonColor: '#3085d6',
        confirmButtonText: "Ok"
      }).then((result: any) => {
        if (result.isConfirmed) {
            this.router.navigate(['auth']);
        }
      })
    });
  }

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

  toggleVisibility1() {
    this.showPassword1 = !this.showPassword1;
  }



  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;
    }
  }


}


