import { type Locator, type Page } from '@playwright/test';
import { BasePage } from './BasePage';
import { ICustomerDetails } from '@business-logic/types/CustomerDetails';

export class PolicyHolderDetailsPage extends BasePage {
    readonly page: Page;
    readonly firstNameTextBox: Locator;
    readonly lastNameTextBox: Locator;
    readonly addressInputBox: Locator;
    readonly emailAddressTextBox: Locator;

    readonly issPageValue = 'policy-holder-details';

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.firstNameTextBox = page.locator('#firstNameField');
        this.lastNameTextBox = page.locator('#lastNameField');
        this.emailAddressTextBox = page.locator('#emailField');
        this.addressInputBox = page.locator('input[name="autocomplete"]'); // for essential flows
    }

    async fillCustomerDetails(customerDetails: ICustomerDetails){
         // Check if firstName field is empty, then fill it
        const firstNameValue = await this.firstNameTextBox.inputValue();
        if (!firstNameValue || firstNameValue.trim() === '') {
            if (customerDetails.firstName) {
                await this.firstNameTextBox.fill(customerDetails.firstName);
            }
        }
    
        // Check if lastName field is empty, then fill it
        const lastNameValue = await this.lastNameTextBox.inputValue();
        if (!lastNameValue || lastNameValue.trim() === '') {
            if (customerDetails.lastName) {
                await this.lastNameTextBox.fill(customerDetails.lastName);
            }
        }

        // Fill email address for both essential and advanced flows
        await this.emailAddressTextBox.fill(customerDetails.email);

        const addressValue = await this.addressInputBox.inputValue();

        // For essential flows, when address fields are not pre-filled
        if (!addressValue || addressValue.trim() === '') {
            await this.addressInputBox.click();
            await this.addressInputBox.fill(customerDetails.address.street);
            
            // Wait for suggestions to load (Google Places has a slight delay)
            await this.page.locator('.pac-item').first().waitFor({ state: 'visible', timeout: 5000 });
            
            // Click the first result
            await this.page.locator('.pac-item').first().click();
            
            // Optional: wait for the input to be populated by Google Places
            await this.addressInputBox.waitFor({ state: 'attached' });
        }
    }
}