import { ToastService } from '@/core/services/toast.service';
import { MustMatch } from '@/core/validators';
import { AppCardComponent, SharedPasswordInputComponent } from '@/shared/components';
import { fieldControl } from '@/shared/constants';
import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { ButtonDirective } from 'primeng/button';
import { finalize } from 'rxjs';
import { ProfileService } from '../services/main.service';

@Component({
  selector: 'partner-reset-password-card',
  templateUrl: './reset-password-card.component.html',
  imports: [ReactiveFormsModule, AppCardComponent, SharedPasswordInputComponent, ButtonDirective],
})
export class PartnerResetPasswordCardComponent {
  private readonly service = inject(ProfileService);
  private readonly fb = inject(FormBuilder);
  private readonly toastService = inject(ToastService);

  readonly loading = signal(false);

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

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

    this.loading.set(true);
    this.service
      .resetPassword({ password: this.form.value.password as string })
      .pipe(finalize(() => this.loading.set(false)))
      .subscribe(() => {
        this.form.reset();
        this.toastService.success({ text: 'گذرواژه با موفقیت به‌روز شد.' });
      });
  }
}
