import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  UntypedFormControl,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';
import { BaseForm } from '@core/base/base-form';
import { ComponentBase } from '@core/base/common-base';
import { AuthService } from '@core/services/authentication/auth.service';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';

@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.scss'],
})
export class ChangePasswordComponent
  extends ComponentBase
  implements BaseForm, OnInit
{
  form!: FormGroup;

  constructor(
    private readonly router: Router,
    private readonly toastr: ToastrService,
    private readonly authSer: AuthService
  ) {
    super();
  }

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.form = new UntypedFormGroup({
      password: new UntypedFormControl(null, [Validators.required]),
      confirm_password: new UntypedFormControl(null, [Validators.required]),
    });
  }

  onSubmit(): void {
    if (super.submitValidity(this.form)) {
      if (
        this.form.get('password')?.value !==
        this.form.get('confirm_password')?.value
      ) {
        this.toastr.warning('Password not equla confirm password !');
        return;
      }
      this.loading = true;
      this.authSer
        .ChnagePassword({
          userId: sessionStorage.getItem('userId')!,
          password: this.form.get('password')?.value,
        })
        .pipe(takeUntil(this.destroy$))
        .subscribe((res) => {
          this.toastr.success('Password Changes Successfully');
          this.loading = false;
          this.router.navigate(['/']);
        });
    }
  }
}
