import { postalCodeValidator } from '@/core/validators';
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 { ICustomerLegalRequest, ICustomerResponse } from '../models';
import { CustomersService } from '../services/main.service';

@Component({
  selector: 'consumer-customer-legal-form',
  templateUrl: './form-legal.component.html',
  imports: [ReactiveFormsModule, InputComponent, FormFooterActionsComponent],
})
export class ConsumerCustomerLegalFormComponent extends AbstractForm<
  ICustomerLegalRequest,
  ICustomerResponse
> {
  @Input({ required: true }) customerId!: string;

  private readonly service = inject(CustomersService);

  private initForm() {
    const form = this.fb.group({
      company_name: [this.initialValues?.legal?.company_name || '', [Validators.required]],
      registration_number: [
        this.initialValues?.legal?.registration_number || '',
        [Validators.required],
      ],
      economic_code: [this.initialValues?.legal?.economic_code || '', [Validators.required]],
      postal_code: [
        this.initialValues?.legal?.postal_code || '',
        [Validators.required, postalCodeValidator()],
      ],
    });
    return form;
  }

  form = this.initForm();

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

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