import { MustMatch, password } from '@/core/validators';
// import { CatalogRolesComponent } from '@/shared/catalog/roles';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { EnumSelectComponent } from '@/shared/apiEnum/select.component';
import { SharedPasswordInputComponent, UsernameComponent } from '@/shared/components';
import { fieldControl } from '@/shared/constants/fields';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { IAccountRequest, IAccountResponse } from '../../models';
import { AdminUserAccountsService } from '../../services/accounts.service';

@Component({
  selector: 'superAdmin-user-account-form',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    SharedDialogComponent,
    UsernameComponent,
    FormFooterActionsComponent,
    EnumSelectComponent,
    SharedPasswordInputComponent,
  ],
})
export class UserAccountFormComponent extends AbstractFormDialog<
  IAccountRequest,
  IAccountResponse
> {
  private readonly service = inject(AdminUserAccountsService);

  @Input() userId!: string;
  @Input() accountId!: string;

  initForm = () => {
    if (this.editMode) {
      return this.fb.group(
        {
          username: fieldControl.username(this.initialValues?.username || ''),
          type: [this.initialValues?.type || '', [Validators.required]],

          password: ['', [password()]],
          confirmPassword: [''],
        },
        {
          validators: [MustMatch('password', 'confirmPassword')],
        },
      );
    }
    return this.fb.group(
      {
        username: fieldControl.username(this.initialValues?.username || ''),
        // @ts-ignore
        type: [this.initialValues?.type || '', [Validators.required]],

        password: ['', [Validators.required, password()]],
        confirmPassword: ['', [Validators.required]],
      },
      {
        validators: [MustMatch('password', 'confirmPassword')],
      },
    );
  };

  form = this.initForm();

  override ngOnChanges(): void {
    this.form = this.initForm();
  }

  submitForm() {
    const formValue = this.form.value as IAccountRequest;
    // @ts-ignore
    const { confirmPassword, ...rest } = formValue;
    if (this.editMode) {
      return this.service.update(this.userId, this.accountId, rest);
    }
    return this.service.create(this.userId, rest);
  }
}
