import { OptionMenu } from '@/manager/shared/components/OptionMenu';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { sleep } from '@/shared/utils/timeout-utils';

export class SingleAutocomplete extends BaseComponent {
  private readonly body = this.host.locator('.v-field:not(.v-field--loading)');
  private readonly input = this.body.locator('input[type=text]');
  private readonly closeButton = this.body.locator('.v-field__clearable');
  readonly menu = new OptionMenu(this.input);

  async select(value: string): Promise<void> {
    await this.input.focus();
    await this.input.clear();
    await this.input.clear();
    await this.input.fill(value);
    await this.menu.select(value);
  }

  async fill(value: string): Promise<void> {
    await this.input.focus();
    await this.input.clear();
    await this.input.clear();
    // TODO: temporary fix for when the autocomplete is not fully loaded yet e.g. due to currently opening a root dialog
    await sleep(75);
    await this.input.fill(value);

    if (value) {
      const menuBody = await this.menu.getBody();
      await menuBody.waitFor();
    }

    await this.input.press('Enter');
  }

  async fillWithoutEnter(value: string): Promise<void> {
    await this.input.focus();
    await this.input.fill('');
    await this.input.fill(value);
  }

  async clear(): Promise<void> {
    await this.closeButton.hover();
    await this.closeButton.click();
  }
}
