import { Component, EventEmitter, Inject, Output } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DataService } from '../data.service';
import {AddUserModalComponent} from "../add-user-modal/add-user-modal.component";
import {ToastrService} from "ngx-toastr";
@Component({
  selector: 'app-change-password-modal',
  templateUrl: './change-password-modal.component.html',
  styleUrl: './change-password-modal.component.css'
})
export class ChangePasswordModalComponent {
  @Output() userEdited = new EventEmitter<void>();
  userForm: FormGroup;
  passwordMismatch: boolean = false;
  updateError: boolean = false;
  loading: boolean = false;
  resetPasswordError: string = '';

  constructor(
    public dialogRef: MatDialogRef<AddUserModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private fb: FormBuilder,
    private dataService: DataService,
    private toastService: ToastrService
  ) {
    this.userForm = this.fb.group({
      currentPassword: ['', Validators.required],
      newPassword: ['', Validators.required],
      repeatNewPassword: ['', Validators.required]
    }, { validators: this.passwordMatchValidator });
  }

  ngOnInit(): void {
    console.log('Data:', this.data);
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  onSubmit(): void {
    if (this.userForm.valid) {
      this.passwordMismatch = false;
      this.updateError = false;
      this.loading = true

      const userPayload = {
        currentPassword: this.userForm.value.currentPassword,
        newPassword: this.userForm.value.newPassword,
        repeatNewPassword: this.userForm.value.repeatNewPassword
      };

      this.dataService.changePassword(this.data.uuid, userPayload).subscribe({
        next: () => {
          this.userEdited.emit();
          this.dialogRef.close();
          this.toastService.success('Contraseña cambiada con éxito');
        },
        error: (err) => {
          console.error('Error changing password:', err);
          this.toastService.error(err.error['hydra:description']);
          this.resetPasswordError = err.error.message;
          this.updateError = true;
          this.loading = false;
        }
      });
    } else {
      console.error('Form is invalid');
      this.passwordMismatch = this.userForm.hasError('mismatch');
      this.updateError = true;
      this.loading = false
    }
  }

  private passwordMatchValidator(form: FormGroup): { [key: string]: boolean } | null {
    return form.get('newPassword')?.value === form.get('repeatNewPassword')?.value ? null : { mismatch: true };
  }
}
