import { BasePage } from '@/manager/shared/base/BasePage';
import { ICustomerListFilter } from '@/manager/modules/customer/types/customer-types';
import { CustomerCreateDialog } from '@/manager/modules/customer/views/CustomerCreateDialog';
import { CustomerDetailsPage } from '@/manager/modules/customer/views/CustomerDetailsPage';
import { DataTable } from '@/manager/modules/ui/data-table/components/DataTable';
import { DebouncedTextField } from '@/manager/shared/components/DebouncedTextField';
import { MultiAutocomplete } from '@/manager/shared/components/MultiAutocomplete';
import { getFilterHost } from '@/manager/shared/utils/host-utils';

export class CustomerListPage extends BasePage {
  readonly actionMenu = this.host.getByTestId('customer-list-action-menu');
  readonly actionMenuButton = this.header.getByTestId('customer-list-action-button');
  readonly actionMenuCreateCustomerItem = this.actionMenu.locator('.v-list-item').nth(0);
  readonly searchTextField = new DebouncedTextField(getFilterHost(this.body, 'Search'));
  readonly locationAutocomplete = new MultiAutocomplete(getFilterHost(this.body, 'Location'));
  readonly hasPastDueInvoicesAutocomplete = new MultiAutocomplete(getFilterHost(this.body, 'Has past due invoice(s)'));
  readonly dataTable = new DataTable(this.body);

  async filter(filter: ICustomerListFilter): Promise<void> {
    filter.search && (await this.searchTextField.fill(filter.search.value));
    filter.locations && (await this.locationAutocomplete.fill(filter.locations.value));
    filter.hasPastDueInvoices && (await this.hasPastDueInvoicesAutocomplete.fill(filter.hasPastDueInvoices.value));
  }

  async openCustomerCreateDialog(): Promise<CustomerCreateDialog> {
    await this.actionMenuButton.click();
    await Promise.all([this.host.waitForURL('/customers/create'), this.actionMenuCreateCustomerItem.click()]);
    return new CustomerCreateDialog(this.host);
  }

  async goToCustomerDetailsPage(index: number): Promise<CustomerDetailsPage> {
    await Promise.all([this.host.waitForURL('**/customers/*'), this.dataTable.clickRow(index)]);
    return new CustomerDetailsPage(this.host);
  }
}
