import { BaseMenu } from '@/manager/shared/base/BaseMenu';
import { Locator } from '@playwright/test';

export class DateMenu extends BaseMenu {
  async select(date: Date): Promise<void> {
    const monthResetButton = await this.getMonthResetButton();
    const yearResetButton = await this.getYearResetButton();
    const yearElement = await this.getYearElement(date.getFullYear());
    const monthElement = await this.getMonthElement(date.getMonth());
    const dayElement = await this.getDayElement(date.getDate());

    await yearResetButton.click();
    await yearElement.click();
    await monthResetButton.click();
    await monthElement.click();
    await dayElement.click();
  }

  async confirm(): Promise<void> {
    const confirmButton = await this.getOptionalConfirmButton();
    await confirmButton.click();
  }

  private async getOptionalConfirmButton(): Promise<Locator> {
    const body = await this.getBody();
    return body.getByRole('button', { name: 'OK' });
  }

  private async getMonthResetButton(): Promise<Locator> {
    const body = await this.getBody();
    return body.getByRole('button', { name: 'Open months overlay' });
  }

  private async getYearResetButton(): Promise<Locator> {
    const body = await this.getBody();
    return body.getByRole('button', { name: 'Open years overlay' });
  }

  private async getDayElement(day: number): Promise<Locator> {
    const body = await this.getBody();
    return body
      .getByRole('gridcell', { name: day.toString(), exact: true })
      .locator('div:not(.dp__cell_disabled):not(.dp__cell_offset)');
  }

  private async getMonthElement(month: number): Promise<Locator> {
    const body = await this.getBody();
    return body.getByRole('gridcell').nth(month);
  }

  private async getYearElement(year: number): Promise<Locator> {
    const body = await this.getBody();
    return body.getByRole('gridcell', { name: year.toString(), exact: true });
  }
}
