import { BaseDialog } from '@/manager/shared/base/BaseDialog';
import { DepositCreateGeneralFieldSet } from '@/manager/modules/deposit/components/DepositCreateGeneralFieldSet';
import { DepositCreateData } from '@/manager/modules/deposit/deposit-types';
import { DepositDetailsPage } from '@/manager/modules/deposit/views/DepositDetailsPage';
import { TaxFieldSet } from '@/manager/modules/ui/tax/components/TaxFieldSet';
import { getDialogErrorsHost, getSnackbarHost } from '@/manager/shared/utils/locator-utils';
import { getDetailsPageRegExpUrl } from '@/manager/shared/utils/url-utils';
import { Page } from '@playwright/test';
import { formatPercentage } from '@/shared/utils/formatters';

export class DepositCreateDialog extends BaseDialog {
  readonly generalFieldSet = new DepositCreateGeneralFieldSet(this.main);
  readonly taxFieldSet = new TaxFieldSet(this.main);
  readonly errors = getDialogErrorsHost(this.main);
  readonly snackbar = getSnackbarHost(this.host, 'Deposit saved successfully');

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

  async goto(): Promise<void> {
    await this.host.goto('/deposits/create');
  }

  async create(data: DepositCreateData): Promise<DepositDetailsPage> {
    await this.fill(data);
    await Promise.all([
      this.snackbar.waitFor(),
      this.host.waitForURL(getDetailsPageRegExpUrl('deposits')),
      this.submit(),
    ]);
    return new DepositDetailsPage(this.host);
  }

  async fill(data: DepositCreateData): Promise<void> {
    await this.generalFieldSet.nameTextField.fill(data.name);
    await this.generalFieldSet.locationAutocomplete.fill(data.location.name);
    await this.generalFieldSet.priceNumberField.fill(data.priceExclVat);

    if (data.taxes.b2b.rate !== 0) {
      await this.taxFieldSet.b2bTaxAutocomplete.select(formatPercentage(data.taxes.b2b.rate));
    }

    if (data.taxes.b2c.rate !== 0) {
      await this.taxFieldSet.b2cTaxAutocomplete.select(formatPercentage(data.taxes.b2c.rate));
    }
  }

  async submit(): Promise<void> {
    await this.submitButton.click();
  }
}
