import { MustMatch, password } from '@/core/validators';
import { AbstractDialog } from '@/shared/abstractClasses/abstract-dialog';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, EventEmitter, Output, input } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { SharedPasswordInputComponent } from '../passwordInput/password-input.component';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';

export interface IChangePasswordSubmitPayload {
  password: string;
  confirmPassword: string;
}

@Component({
  selector: 'shared-change-password-form-dialog',
  templateUrl: './change-password-form-dialog.component.html',
  imports: [ReactiveFormsModule, SharedDialogComponent, FormFooterActionsComponent, SharedPasswordInputComponent],
})
export class ChangePasswordFormDialogComponent extends AbstractDialog {
  title = input<string>('');
  loading = input<boolean>(false);

  @Output() onSubmit = new EventEmitter<IChangePasswordSubmitPayload>();

  private readonly fb = new FormBuilder();

  form = this.fb.group(
    {
      password: ['', [Validators.required, password()]],
      confirmPassword: ['', [Validators.required]],
    },
    {
      validators: [MustMatch('password', 'confirmPassword')],
    },
  );

  get dialogHeader() {
    return this.title() ? `تغییر گذرواژه ${this.title()}` : 'تغییر گذرواژه';
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.invalid) {
      return;
    }

    this.onSubmit.emit(this.form.getRawValue() as IChangePasswordSubmitPayload);
  }

  override close() {
    this.form.reset();
    super.close();
  }
}
