import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { CreateEventPage } from './pages/CreateEventPage';
import { EventSummaryPage } from './pages/EventSummaryPage';
import { ModifyEventPage } from './pages/ModifyEventPage';
import { TEST_USERS } from './data/test-users';
import { TEST_EVENTS } from './data/test-events';

// STAGING_URL is now imported from config

test.describe('Modify Event Test from My Events', () => {
    let loginPage: LoginPage;
    let dashboardPage: DashboardPage;
    let createEventPage: CreateEventPage;
    let eventSummaryPage: EventSummaryPage;
    let modifyEventPage: ModifyEventPage;
    
    const trainer = TEST_USERS.trainer;

    test.beforeEach(async ({ page }) => {
        loginPage = new LoginPage(page);
        dashboardPage = new DashboardPage(page);
        createEventPage = new CreateEventPage(page);
        eventSummaryPage = new EventSummaryPage(page);
        modifyEventPage = new ModifyEventPage(page);
        
        // Set base URL and login
        page.context().setDefaultNavigationTimeout(TIMEOUTS.navigation);
        await page.goto(STAGING_URL);
        await loginPage.navigateToLogin();
        await loginPage.login(trainer.username, trainer.password);
    });

    test('Create and Modify Event from My Events Page', async ({ page }) => {
        // First create an event
        await dashboardPage.clickCreateEvent();
        await expect(page).toHaveURL(/.*manage-event/);
        
        // Fill event details
        const eventData = TEST_EVENTS.basicEvent;
        await createEventPage.fillEventDetails(eventData);
        
        // Submit event
        await createEventPage.submitEvent();
        
        // Wait for success
        await page.waitForLoadState('networkidle');
        
        // Navigate to My Events page
        await page.goto(`${STAGING_URL}/my-events/`);
        await page.waitForLoadState('networkidle');
        await page.screenshot({ path: 'test-results/screenshots/my-events-after-create.png' });
        
        // Look for event links on My Events page
        const eventLinks = page.locator('a.url');
        const linkCount = await eventLinks.count();
        console.log('Number of event links found:', linkCount);
        
        if (linkCount > 0) {
            // Get the first event link text
            const firstEventTitle = await eventLinks.first().innerText();
            console.log('First event title:', firstEventTitle);
            
            // Click the first event
            await eventLinks.first().click();
            await page.waitForLoadState('networkidle');
            
            const eventDetailUrl = page.url();
            console.log('Event detail URL:', eventDetailUrl);
            await page.screenshot({ path: 'test-results/screenshots/event-detail-from-my-events.png' });
            
            // Look for an Edit button/link on the event detail page
            const editLinks = page.locator('a:has-text("Edit")');
            const editButton = page.locator('button:has-text("Edit")');
            const modifyLink = page.locator('a:has-text("Modify")');
            
            let foundEditOption = false;
            
            if (await editLinks.count() > 0) {
                console.log('Found Edit link');
                await editLinks.first().click();
                foundEditOption = true;
            } else if (await editButton.count() > 0) {
                console.log('Found Edit button');
                await editButton.first().click();
                foundEditOption = true;
            } else if (await modifyLink.count() > 0) {
                console.log('Found Modify link');
                await modifyLink.first().click();
                foundEditOption = true;
            }
            
            if (foundEditOption) {
                await page.waitForLoadState('networkidle');
                const modifyUrl = page.url();
                console.log('Modify page URL:', modifyUrl);
                await page.screenshot({ path: 'test-results/screenshots/modify-event-page-from-my-events.png' });
                
                // Modify the event
                const updatedEvent = {
                    ...TEST_EVENTS.basicEvent,
                    title: 'Updated HVAC Training Session',
                    description: 'This training session has been updated with new content.'
                };
                
                await modifyEventPage.fillEventDetails(updatedEvent);
                
                // Check for update button
                if (await modifyEventPage.isUpdateButtonVisible()) {
                    console.log('Update button found, clicking it');
                    await modifyEventPage.updateEvent();
                } else {
                    console.log('Update button not found, trying submit button');
                    await createEventPage.submitEvent();
                }
                
                await page.waitForLoadState('networkidle');
                await page.screenshot({ path: 'test-results/screenshots/after-update-from-my-events.png' });
                
                const afterUpdateUrl = page.url();
                console.log('After update URL:', afterUpdateUrl);
            } else {
                console.log('No edit option found on event detail page');
                
                // Try going back to My Events to look for edit option there
                await page.goto(`${STAGING_URL}/my-events/`);
                await page.waitForLoadState('networkidle');
                
                // Look for edit links in the event list
                const eventRows = page.locator('tr.community-events-event-row');
                const rowCount = await eventRows.count();
                console.log('Event rows found:', rowCount);
                
                if (rowCount > 0) {
                    const firstRow = eventRows.first();
                    const editLinkInRow = firstRow.locator('a:has-text("Edit")');
                    
                    if (await editLinkInRow.count() > 0) {
                        console.log('Found Edit link in event row');
                        await editLinkInRow.click();
                        await page.waitForLoadState('networkidle');
                        
                        const editPageUrl = page.url();
                        console.log('Edit page URL from row:', editPageUrl);
                        await page.screenshot({ path: 'test-results/screenshots/edit-page-from-row.png' });
                    }
                }
            }
        } else {
            console.log('No event links found on My Events page');
            
            // Check if events are in past events tab
            const pastEventsTab = page.locator('a:has-text("PAST EVENTS")');
            if (await pastEventsTab.count() > 0) {
                await pastEventsTab.click();
                await page.waitForLoadState('networkidle');
                await page.screenshot({ path: 'test-results/screenshots/past-events-tab.png' });
            }
        }
    });
});