import { BaseDialog } from '@/manager/shared/base/BaseDialog';
import { CustomerCreateAccountingFieldSet } from '@/manager/modules/customer/components/CustomerCreateAccountingFieldSet';
import { CustomerCreateAddressFieldSet } from '@/manager/modules/customer/components/CustomerCreateAddressFieldSet';
import { CustomerCreateGeneralFieldSet } from '@/manager/modules/customer/components/CustomerCreateGeneralFieldSet';
import { ICustomerCreateData } from '@/manager/modules/customer/types/customer-types';
import { CustomerDetailsPage } from '@/manager/modules/customer/views/CustomerDetailsPage';
import { getSnackbarHost, getDialogErrorsHost } from '@/manager/shared/utils/host-utils';
import { getDetailsPageRegExpUrl } from '@/manager/shared/utils/url-utils';
import { Page } from '@playwright/test';

export class CustomerCreateDialog extends BaseDialog {
  readonly generalFieldSet = new CustomerCreateGeneralFieldSet(this.main);
  readonly accountingFieldSet = new CustomerCreateAccountingFieldSet(this.main);
  readonly addressFieldSet = new CustomerCreateAddressFieldSet(this.main);
  readonly errors = getDialogErrorsHost(this.main);
  readonly snackbar = getSnackbarHost(this.host, 'Customer created successfully');

  constructor(host: Page) {
    super(host, 'customer-create-dialog');
  }

  async create(data: ICustomerCreateData): Promise<CustomerDetailsPage> {
    await this.fill(data);
    return this.submit();
  }

  async fill(data: ICustomerCreateData): Promise<void> {
    await this.generalFieldSet.customerTypeAutocomplete.fill(data.type);
    await this.generalFieldSet.locationsAutocomplete.fill(data.locations);

    if (data.type === 'business') {
      data.companyName != null && (await this.generalFieldSet.companyNameTextField.fill(data.companyName));
      data.vatNumber != null && (await this.generalFieldSet.vatNumberTextField.fill(data.vatNumber ?? ''));
    }

    data.firstName != null && (await this.generalFieldSet.firstNameTextField.fill(data.firstName));
    data.lastName != null && (await this.generalFieldSet.lastNameTextField.fill(data.lastName));

    await this.generalFieldSet.emailTextField.fill(data.email);
    await this.generalFieldSet.phoneField.fill(data.phone, data.country.name);
    await this.generalFieldSet.languageAutocomplete.fill(data.language.name);
    await this.addressFieldSet.streetTextField.fill(data.street);
    await this.addressFieldSet.postalCodeTextField.fill(data.postalCode);
    await this.addressFieldSet.cityTextField.fill(data.city);
    await this.addressFieldSet.countryAutocomplete.fill(data.country.name);
  }

  async submit(): Promise<CustomerDetailsPage> {
    await Promise.all([
      this.snackbar.waitFor(),
      this.host.waitForURL(getDetailsPageRegExpUrl('customers')),
      this.submitButton.click(),
    ]);
    return new CustomerDetailsPage(this.host);
  }
}
