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 { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { IPartnerAccountRequest, IPartnerAccountResponse } from '../../models';
import { AdminPartnerAccountsService } from '../../services/accounts.service';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';

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

  @Input({ required: true }) partnerId!: string;
  @Input() accountId!: string;

  initForm = () => {
    return this.fb.group(
      {
        username: fieldControl.username(this.initialValues?.account?.username || ''),
        role: [this.initialValues?.role || '', [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 IPartnerAccountRequest;
    // @ts-ignore
    const { confirmPassword, ...rest } = formValue;
    if (this.editMode) {
      return this.service.update(this.partnerId, this.accountId, rest);
    }
    return this.service.create(this.partnerId, rest);
  }
}
