import { BaseComponent } from '@/shared/base/BaseComponent';
import { getMonthDiff } from '@/shared/utils/date-utils';
import { Locator } from '@playwright/test';

export class DatePicker extends BaseComponent {
  private readonly body = this.host.locator('.dp__calendar').first();
  private readonly header = this.host.locator('.dp--header-wrap');
  private readonly nextButton = this.header.locator('[data-dp-element=action-next]');

  async select(date: Date): Promise<void> {
    const day = date.getDate();
    const monthDiff = getMonthDiff(new Date(), date);

    for (let clicked = 0; clicked < monthDiff; clicked++) {
      await this.nextButton.click();
    }

    await this.getDayCell(day).click();
  }

  private getDayCell(day: number): Locator {
    return this.body.locator(
      `[role=gridcell]:has(div:not(.dp__cell_disabled):not(.dp__cell_offset):text-is("${day}"))`
    );
  }
}
