import { BaseDialog } from '@/manager/shared/base/BaseDialog';
import { DiscountBillingPlanList } from '@/manager/modules/discount/components/DiscountBillingPlanList';
import { IDiscountBillingPlan } from '@/manager/modules/discount/types/discount-types';
import { getSnackbarHost } from '@/manager/shared/utils/host-utils';
import { formatBillingPeriod } from '@/shared/utils/format-utils';
import { Locator, Page } from '@playwright/test';

export class DiscountEditBillingPlansDialog extends BaseDialog {
  readonly list: DiscountBillingPlanList;
  readonly updatedSnackbar: Locator;
  readonly notEmptySnackbar: Locator;

  constructor(
    host: Page,
    readonly showUpdatedSnackbar: boolean
  ) {
    super(host, 'discount-edit-billing-plans-dialog');
    this.list = new DiscountBillingPlanList(this.main);
    this.updatedSnackbar = getSnackbarHost(this.host, 'Discount successfully updated');
    this.notEmptySnackbar = getSnackbarHost(this.host, 'Please provide at least one booking plan or product.');
  }

  async addAll(): Promise<void> {
    await this.list.dataTable.selectRowsPerPage(100);
    return this.list.dataTable.rowSelector.selectAll();
  }

  async removeAll(): Promise<void> {
    await this.list.dataTable.selectRowsPerPage(100);
    return this.list.dataTable.rowSelector.deselectAll();
  }

  async add(billingPlans: IDiscountBillingPlan[]): Promise<void> {
    for (const billingPlan of billingPlans) {
      await this.filterAndHandleSelection(billingPlan, true);
    }
  }

  async remove(billingPlans: IDiscountBillingPlan[]): Promise<void> {
    for (const billingPlan of billingPlans) {
      await this.filterAndHandleSelection(billingPlan, false);
    }
  }

  async submit(): Promise<void> {
    const tasks = [this.submitButton.click()];

    if (this.showUpdatedSnackbar) {
      tasks.unshift(this.updatedSnackbar.waitFor());
    }

    await Promise.all(tasks);
  }

  private async filterAndHandleSelection(billingPlan: IDiscountBillingPlan, select: boolean): Promise<void> {
    await this.list.searchTextField.fill(billingPlan.name ?? '');
    await this.list.unitTypeAutocomplete.fill(billingPlan.unitType);
    await this.list.billingPeriodAutocomplete.fill(formatBillingPeriod(billingPlan.type, billingPlan.amount));
    return select ? this.list.dataTable.rowSelector.select(0) : this.list.dataTable.rowSelector.deselect(0);
  }
}
