import { Component, OnDestroy } from '@angular/core';
import { AbstractControl, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { PayerEditComponent } from './payer-edit.component';

@Component({
  selector: 'page-payer-edit-b2c',
  templateUrl: 'payer-edit-b2c.component.html',
  styleUrls: ['../address.component.scss'],
})
export class PayerEditB2CComponent extends PayerEditComponent implements OnDestroy {
  formsSubscription: Subscription;

  get organisationGroup(): AbstractControl {
    return this.control?.get('organisation');
  }

  ngOnDestroy(): void {
    if (this.formsSubscription) {
      this.formsSubscription.unsubscribe();
    }
  }

  async initForm() {
    const fb = this.fb;
    const payerDTO = await this.payer$.toPromise();
    const isDefault = await this.isDefault$.toPromise();

    this.control = fb.group({
      gender: fb.control(payerDTO?.gender || undefined, [Validators.required, Validators.min(1)]),
      title: fb.control(payerDTO?.title),
      firstName: fb.control(payerDTO?.firstName, [Validators.required]),
      lastName: fb.control(payerDTO?.lastName, [Validators.required]),
      organisation: fb.group({
        name: fb.control(payerDTO?.organisation?.name),
        department: fb.control(payerDTO?.organisation?.department),
        vatId: fb.control(payerDTO?.organisation?.vatId),
      }),
      address: fb.group({
        street: fb.control(payerDTO?.address?.street, [Validators.required]),
        streetNumber: fb.control(payerDTO?.address?.streetNumber, [Validators.required]),
        zipCode: fb.control(payerDTO?.address?.zipCode, [Validators.required]),
        city: fb.control(payerDTO?.address?.city, [Validators.required]),
        info: fb.control(payerDTO?.address?.info),
        country: fb.control(payerDTO?.address?.country || 'DEU', [Validators.required]),
      }),
      isDefault: fb.control(isDefault),
    });
    this.cdr.markForCheck();

    this.formsSubscription = this.organisationGroup?.get('name').valueChanges.subscribe((value: string) => {
      if (!value) {
        this.organisationGroup.get('department').reset('', { onlySelf: true });
        this.organisationGroup.get('vatId').reset('', { onlySelf: true });
      }
    });
  }
}
