import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { validateEmail } from '../../../validators/email-validator';
import { organisationB2bDeliveryValidator } from '../../../validators/organisation-delivery-b2b-validator';
import { ShippingEditComponent } from './shipping-edit.component';

@Component({
  selector: 'page-shipping-edit-b2b',
  templateUrl: 'shipping-edit-b2b.component.html',
  styleUrls: ['../address.component.scss'],
})
export class ShippingEditB2BComponent extends ShippingEditComponent {
  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]),
        }),
        communicationDetails: fb.group({
          email: fb.control(shippingAddressDTO?.communicationDetails?.email, [validateEmail]),
          phone: fb.control(shippingAddressDTO?.communicationDetails?.phone),
          mobile: fb.control(shippingAddressDTO?.communicationDetails?.mobile),
        }),
        isDefault: fb.control(isDefault),
      },
      { validators: organisationB2bDeliveryValidator() }
    );
    this.cdr.markForCheck();
  }
}
