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 { IConsumerAccountRequest, IConsumerAccountResponse } from '../../models';
import { PartnerConsumerAccountsService } from '../../services/accounts.service';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';

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

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

  initForm = () => {
    if (this.editMode) {
      return this.fb.group(
        {
          username: fieldControl.username(this.initialValues?.account.username || ''),
          password: ['', [password()]],
          confirmPassword: [''],
        },
        {
          validators: [MustMatch('password', 'confirmPassword')],
        },
      );
    }
    return this.fb.group(
      {
        username: fieldControl.username(this.initialValues?.account.username || ''),
        role: ['', [Validators.required]],
        password: ['', [Validators.required, password()]],
        confirmPassword: ['', [Validators.required]],
      },
      {
        validators: [MustMatch('password', 'confirmPassword')],
      },
    ) as any;
  };

  form = this.initForm();

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

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