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

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

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

  ngOnInit(): void {
    super.ngOnInit();
    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 });
      }
    });
  }

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

  initForm(): FormGroup {
    const fb = this.fb;

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