import { Component, OnDestroy, OnInit } from '@angular/core';
import { AbstractControl, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { ShippingEditComponent } from './shipping-edit.component';

@Component({
  selector: 'page-shipping-edit-b2c',
  templateUrl: 'shipping-edit-b2c.component.html',
  styleUrls: ['../address.component.scss'],
})
export class ShippingEditB2CComponent extends ShippingEditComponent implements OnDestroy {
  formSubscription: Subscription;

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

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

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

  async initForm() {
    const fb = this.fb;
    const shippingAddressDTO = await this.shippingAddress$.toPromise();
    const isDefault = await this.isDefault$.toPromise();

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