// import { CatalogRolesComponent } from '@/shared/catalog/roles';
import { postalCodeValidator } from '@/core/validators';
import { nationalIdValidator } from '@/core/validators/national-id.validator';
import { AbstractForm } from '@/shared/abstractClasses';
import { InputComponent } from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { tap } from 'rxjs';
import { ICustomerIndividualRequest, ICustomerResponse } from '../models';
import { CustomersService } from '../services/main.service';

@Component({
  selector: 'consumer-customer-form-individual',
  templateUrl: './form-individual.component.html',
  imports: [ReactiveFormsModule, InputComponent, FormFooterActionsComponent],
})
export class ConsumerCustomerIndividualFormComponent extends AbstractForm<
  ICustomerIndividualRequest,
  ICustomerResponse
> {
  private readonly service = inject(CustomersService);

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

  initForm = () => {
    return this.fb.group({
      first_name: [this.initialValues?.individual?.first_name || '', [Validators.required]],
      last_name: [this.initialValues?.individual?.last_name || '', [Validators.required]],
      national_code: [
        this.initialValues?.individual?.national_id || '',
        [Validators.required, nationalIdValidator()],
      ],
      economic_code: [this.initialValues?.individual?.economic_code || ''],
      postal_code: [
        this.initialValues?.individual?.postal_code || '',
        [Validators.required, postalCodeValidator()],
      ],
    });
  };

  form = this.initForm();

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

  submitForm() {
    const formValue = this.form.value as ICustomerIndividualRequest;
    return this.service.updateIndividualCustomer(this.customerId, formValue).pipe(
      tap((res) => {
        if (res) {
          this.onClose.emit();
        }
      }),
    );
  }
}
