import { BasePage } from '@/manager/shared/base/BasePage';
import { DataTable } from '@/manager/modules/ui/data-table/components/DataTable';
import { IUnitListFilter } from '@/manager/modules/unit/types/unit-types';
import { UnitCreateDialog } from '@/manager/modules/unit/views/UnitCreateDialog';
import { UnitDetailsPage } from '@/manager/modules/unit/views/UnitDetailsPage';
import { DebouncedTextField } from '@/manager/shared/components/DebouncedTextField';
import { MultiAutocomplete } from '@/manager/shared/components/MultiAutocomplete';
import { getFilterHost } from '@/manager/shared/utils/host-utils';

export class UnitListPage extends BasePage {
  readonly actionMenu = this.host.getByTestId('unit-list-action-menu');
  readonly actionMenuButton = this.header.getByTestId('unit-list-action-button');
  readonly actionMenuCreateUnitItem = 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 unitTypeSizeAutocomplete = new MultiAutocomplete(getFilterHost(this.body, 'Size'));
  readonly statusAutocomplete = new MultiAutocomplete(getFilterHost(this.body, 'Status'));
  readonly dataTable = new DataTable(this.body);

  async filter(filter: IUnitListFilter): Promise<void> {
    filter.search && (await this.searchTextField.fill(filter.search));
    filter.locations && (await this.locationAutocomplete.fill(filter.locations));
    filter.unitTypeSizes && (await this.unitTypeSizeAutocomplete.fill(filter.unitTypeSizes));
    filter.status && (await this.statusAutocomplete.fill(filter.status));
  }

  async openUnitCreateDialog(): Promise<UnitCreateDialog> {
    await this.dataTable.waitForLoading();
    await this.actionMenuButton.click();
    await Promise.all([this.host.waitForURL('/units/create'), this.actionMenuCreateUnitItem.click()]);
    return new UnitCreateDialog(this.host);
  }

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