import { SingleAutocomplete } from '@/manager/shared/components/SingleAutocomplete';
import { getInputHostByLabel } from '@/manager/shared/utils/locator-utils';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { Locator } from '@playwright/test';

export class BookingAdjustmentRecurringProductsTable extends BaseComponent {
  readonly main = this.host.getByTestId('adjust-booking-recurring-products');
  readonly rows = this.main.getByTestId('adjust-booking-recurring-product-row');
  readonly addButton = this.main.getByTestId('adjust-booking-add-recurring-product-button');
  readonly addedProductAutocomplete = new SingleAutocomplete(
    getInputHostByLabel(this.rows.last(), 'Recurring product')
  );

  async add(productName: string, quantity: number): Promise<void> {
    await this.addButton.click();
    await this.addedProductAutocomplete.select(productName);

    if (quantity !== 1) {
      await this.fillQuantity(this.rows.last(), quantity);
    }
  }

  async setQuantity(productName: string, quantity: number): Promise<void> {
    await this.fillQuantity(this.getRow(productName), quantity);
  }

  async remove(productName: string): Promise<void> {
    await this.getRow(productName).getByTestId('adjust-booking-recurring-product-remove-button').click();
  }

  private getRow(productName: string): Locator {
    return this.rows.filter({ hasText: productName });
  }

  private async fillQuantity(row: Locator, quantity: number): Promise<void> {
    await row.getByTestId('adjust-booking-recurring-product-quantity').locator('input').fill(String(quantity));
  }
}
