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('Test Draft 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 Event and Check All Tabs', async ({ page }) => {
        // First check the dashboard to see if there are any existing events
        await page.waitForLoadState('networkidle');
        const dashboardEventCount = await dashboardPage.getEventCount();
        console.log('Initial dashboard event count:', dashboardEventCount);
        
        // Create an event with today's date
        await dashboardPage.clickCreateEvent();
        await expect(page).toHaveURL(/.*manage-event/);
        
        // Get today's date
        const today = new Date();
        const monthStr = (today.getMonth() + 1).toString();
        const dayStr = today.getDate().toString();
        const yearStr = today.getFullYear().toString();
        const todayFormatted = `${monthStr}/${dayStr}/${yearStr}`;
        
        // Fill event details with today's date
        const eventData = {
            ...TEST_EVENTS.basicEvent,
            startDate: todayFormatted,
            endDate: todayFormatted,
            title: `HVAC Training Today ${Date.now()}` // Unique title
        };
        
        console.log('Creating event with date:', todayFormatted);
        await createEventPage.fillEventDetails(eventData);
        
        // Submit event
        await createEventPage.submitEvent();
        await page.waitForLoadState('networkidle');
        
        // Check the VIEW YOUR SUBMITTED EVENTS button
        const viewEventsButton = page.locator('text="VIEW YOUR SUBMITTED EVENTS"');
        if (await viewEventsButton.isVisible()) {
            await viewEventsButton.click();
            await page.waitForLoadState('networkidle');
        }
        
        const afterSubmitUrl = page.url();
        console.log('After submit URL:', afterSubmitUrl);
        await page.screenshot({ path: 'test-results/screenshots/after-create-event.png' });
        
        // Check status tabs on My Events page
        const urls = [
            `/my-events/`,
            `/my-events/?tribe-bar-event-status=publish`,
            `/my-events/?tribe-bar-event-status=draft`,
            `/my-events/?tribe-bar-event-status=pending`,
            `/my-events/?tribe-bar-event-status=private`
        ];
        
        const statuses = ['All', 'Published', 'Draft', 'Pending', 'Private'];
        
        for (let i = 0; i < urls.length; i++) {
            await page.goto(`${STAGING_URL}${urls[i]}`);
            await page.waitForLoadState('networkidle');
            console.log(`\n${statuses[i]} Events:`);
            
            // Check if there are events in the table
            const eventRows = page.locator('tr.community-events-event-row');
            const rowCount = await eventRows.count();
            console.log(`Event rows found: ${rowCount}`);
            
            if (rowCount > 0) {
                // Get the first event details
                const firstRow = eventRows.first();
                const title = await firstRow.locator('a.url').innerText();
                const statusElement = await firstRow.locator('td').first();
                const statusText = await statusElement.innerText();
                
                console.log(`First event title: ${title}`);
                console.log(`Status: ${statusText}`);
                
                // Check for Edit link
                const editLink = firstRow.locator('a:has-text("Edit")');
                if (await editLink.count() > 0) {
                    console.log('Edit link found');
                    
                    // Click Edit link to test modification
                    await editLink.click();
                    await page.waitForLoadState('networkidle');
                    
                    const editUrl = page.url();
                    console.log('Edit page URL:', editUrl);
                    await page.screenshot({ path: `test-results/screenshots/edit-${statuses[i].toLowerCase()}-event.png` });
                    
                    // Try to modify the event
                    const updatedEvent = {
                        ...eventData,
                        title: `Updated ${title}`,
                        description: 'This event has been updated.'
                    };
                    
                    await modifyEventPage.fillEventDetails(updatedEvent);
                    
                    // Check for Update button
                    if (await modifyEventPage.isUpdateButtonVisible()) {
                        console.log('Update button found');
                        await modifyEventPage.updateEvent();
                    } else {
                        console.log('Update button not found, trying submit');
                        await createEventPage.submitEvent();
                    }
                    
                    await page.waitForLoadState('networkidle');
                    const afterUpdateUrl = page.url();
                    console.log('After update URL:', afterUpdateUrl);
                    
                    // Go back to My Events
                    await page.goto(`${STAGING_URL}/my-events/`);
                    await page.waitForLoadState('networkidle');
                    break; // Only test modification on the first found event
                }
            }
            
            await page.screenshot({ path: `test-results/screenshots/my-events-${statuses[i].toLowerCase()}.png` });
        }
        
        // Finally, check the dashboard again
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        const finalDashboardCount = await dashboardPage.getEventCount();
        console.log('Final dashboard event count:', finalDashboardCount);
        await page.screenshot({ path: 'test-results/screenshots/final-dashboard.png' });
    });
});