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: 'Select month' });
  }

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

  private async getDayElement(day: number): Promise<Locator> {
    const body = await this.getBody();
    return body
      .locator('.v-date-picker-month__day:not(.v-date-picker-month__day--adjacent)')
      .locator('button.v-date-picker-month__day-btn')
      .nth(day - 1);
  }

  private async getMonthElement(month: number): Promise<Locator> {
    const body = await this.getBody();
    return body.locator('.v-date-picker-months__content').getByRole('button').nth(month);
  }

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