import { expect, type Locator, type Page } from '@playwright/test';
import { BasePage } from './BasePage';
import { IAppointmentDetails } from '@business-logic/types/CustomerDetails';
import { formatDate, formatTime } from '@impl/utils/DateUtils';
import { AppointmentType, ServiceLocation } from '@business-logic/types/Enums';

export class SchedulePage extends BasePage {
    readonly page: Page;
    url = process.env['BASE_URL']! + '/fmg/?fmgPage=schedule';
    readonly firstAvailableDate: Locator;
    readonly firstAvailableTime: Locator;
    readonly modalContinueButton: Locator;
    readonly dropOffButton: Locator;
    readonly dateText: Locator;
    readonly viewMoreDatesLink: Locator;

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.firstAvailableDate = this.page.locator('.selectable-day').locator('nth=0');
        this.firstAvailableTime = this.page.locator('label').filter({ hasText: /AM|PM/ }).locator('div').locator('nth=0');
        this.modalContinueButton = this.page.getByRole('dialog').getByRole('button', { name: 'Continue' });
        this.dropOffButton = this.page.getByText('Drop off your vehicle', { exact: true });
        this.dateText = this.page.locator('label.modal-title');
        this.viewMoreDatesLink = this.page.getByText(/View more dates/).first();
    }

    async scheduleAppointment(appointmentDetails: IAppointmentDetails) {
        const formattedDate = formatDate(appointmentDetails.appointmentDate!);
        const formattedTime = formatTime(appointmentDetails.appointmentDate!);
        const dateInput = this.page.locator(`div[id="${formattedDate}"]`);
        const timeButton = this.page.locator(`div[aria-label="${formattedTime}"]`);
        if (await dateInput.isVisible()) {
            await dateInput.click();
        } else {
            await this.viewMoreDatesLink.click();
            await dateInput.click();
        }
        await timeButton.click();
        await this.modalContinueButton.click();
    }

    async scheduleFirstAppointment(serviceLocation: AppointmentType) {
        if (await this.firstAvailableDate.isVisible()) {
            await this.firstAvailableDate.click();
        } else {
            await this.viewMoreDatesLink.click();
            while(await this.firstAvailableDate.isHidden()){
                await this.viewMoreDatesLink.click();
            }
            await this.firstAvailableDate.click();
        }

        serviceLocation === AppointmentType.DropOff ? await this.dropOffButton.click() : await this.firstAvailableTime.click();
        const apptDate = `${await this.dateText.allInnerTexts()}`
        await this.modalContinueButton.click();
        return (apptDate);
    }
}