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

export class VerifyDetailsPage extends InsuranceBasePage {
    readonly page: Page;
    readonly policyNumberTextBox: Locator;
    readonly policyZipTextBox: Locator;
    readonly damageDate: Locator;

    url = process.env['BASE_URL']! + '/FixMyGlass/VerifyDetails.aspx';

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.policyNumberTextBox = page.locator('#PolicyNumber');
        this.policyZipTextBox = page.locator('#PolicyZip');
        this.damageDate = page.locator('#LossDate');
        // this.validateURL(this.url);
    }

    async verifyPolicyDetails(customerDetails: ICustomerDetails, claimDetails: IClaimDetails): Promise<void> {
        // Format the date from YYYY-MM-DD to MM/DD/YYYY if needed
        const formattedDate = this.formatDate(claimDetails.damageDate);
        
        // Check and fill policy number
        await this.verifyAndFillField(
            this.policyNumberTextBox, 
            claimDetails.policyNumber,
            'Policy Number'
        );
        
        // Check and fill zip code
        await this.verifyAndFillField(
            this.policyZipTextBox, 
            customerDetails.address.postalCode,
            'Policy ZIP'
        );
        
        // Check and fill damage date
        await this.verifyAndFillField(
            this.damageDate, 
            formattedDate,
            'Damage Date'
        );
    }
    
    private async verifyAndFillField(element: Locator, expectedValue: string, fieldName: string): Promise<void> {
        await element.waitFor({ state: 'visible' });
        const currentValue = await element.inputValue();
        
        if (currentValue !== expectedValue) {
            console.log(`${fieldName} requires correction: Current value '${currentValue}' doesn't match expected '${expectedValue}'`);
            await element.clear();
            await element.fill(expectedValue);
            console.log(`${fieldName} updated to: ${expectedValue}`);
        } else {
            console.log(`${fieldName} verified: ${currentValue}`);
        }
    }
    
    private formatDate(date: string): string {
        // If the date is already in MM/DD/YYYY format, return it as is
        if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(date)) {
            return date;
        }
        
        // If the date is in YYYY-MM-DD format, convert it
        if (/^\d{4}-\d{1,2}-\d{1,2}$/.test(date)) {
            const [year, month, day] = date.split('-');
            return `${month}/${day}/${year}`;
        }
        
        // Return the original string if format is unknown
        return date;
    }
}