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 { TEST_USERS } from './data/test-users';
import { TEST_EVENTS } from './data/test-events';

// STAGING_URL is now imported from config

test.describe('Test Event Creation with Venue and Organizer', () => {
    let loginPage: LoginPage;
    let dashboardPage: DashboardPage;
    let createEventPage: CreateEventPage;
    
    const trainer = TEST_USERS.trainer;

    test.beforeEach(async ({ page }) => {
        loginPage = new LoginPage(page);
        dashboardPage = new DashboardPage(page);
        createEventPage = new CreateEventPage(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 with Venue and Organizer Details', async ({ page }) => {
        // Navigate to create event
        await dashboardPage.clickCreateEvent();
        await expect(page).toHaveURL(/.*manage-event/);
        
        // Fill event details
        const eventData = {
            ...TEST_EVENTS.basicEvent,
            title: `Test Event ${Date.now()}`
        };
        await createEventPage.fillEventDetails(eventData);
        
        // Now handle venue and organizer
        // For Venue - try to fill in the create new venue fields
        const venueSection = page.locator('.venue');
        
        // Fill venue details if fields are available
        const venueName = page.locator('input[name="venue[Venue]"]');
        if (await venueName.count() > 0) {
            await venueName.fill('Test Training Center');
        }
        
        const venueAddress = page.locator('input[name="venue[Address]"]');
        if (await venueAddress.count() > 0) {
            await venueAddress.fill('123 Test Street');
        }
        
        const venueCity = page.locator('input[name="venue[City]"]');
        if (await venueCity.count() > 0) {
            await venueCity.fill('Test City');
        }
        
        const venueState = page.locator('input[name="venue[State]"], input[name="venue[Province]"]');
        if (await venueState.count() > 0) {
            await venueState.first().fill('CA');
        }
        
        const venueZip = page.locator('input[name="venue[Zip]"]');
        if (await venueZip.count() > 0) {
            await venueZip.fill('12345');
        }
        
        // For Organizer - try to fill in the create new organizer fields
        const organizerSection = page.locator('.organizer');
        
        const organizerName = page.locator('input[name="organizer[Organizer]"]');
        if (await organizerName.count() > 0) {
            await organizerName.fill('Test Training Company');
        }
        
        const organizerPhone = page.locator('input[name="organizer[Phone]"]');
        if (await organizerPhone.count() > 0) {
            await organizerPhone.fill('555-0123');
        }
        
        const organizerEmail = page.locator('input[name="organizer[Email]"]');
        if (await organizerEmail.count() > 0) {
            await organizerEmail.fill('trainer@example.com');
        }
        
        const organizerWebsite = page.locator('input[name="organizer[Website]"]');
        if (await organizerWebsite.count() > 0) {
            await organizerWebsite.fill('https://example.com');
        }
        
        // Take a screenshot before submission
        await page.screenshot({ path: 'test-results/screenshots/event-with-venue-organizer.png' });
        
        // Submit event
        await createEventPage.submitEvent();
        
        // Wait for response
        await page.waitForLoadState('networkidle');
        
        const currentUrl = page.url();
        console.log('After submit URL:', currentUrl);
        
        // Check if the submission was successful
        const viewEventsButton = page.locator('text="VIEW YOUR SUBMITTED EVENTS"');
        if (await viewEventsButton.isVisible()) {
            console.log('Event created successfully!');
            await viewEventsButton.click();
            await page.waitForLoadState('networkidle');
            
            const myEventsUrl = page.url();
            console.log('My Events URL:', myEventsUrl);
            
            // Check if the event appears in the 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 title = await firstRow.locator('a.url').innerText();
                console.log('Event title:', title);
            }
        } else {
            // Check for errors
            const errors = await page.locator('.tribe-community-notice, .error, .warning').all();
            for (const error of errors) {
                const text = await error.innerText();
                console.log('Error:', text);
            }
            
            await page.screenshot({ path: 'test-results/screenshots/event-submission-failed.png' });
        }
        
        // Finally check the dashboard
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        const dashboardEventCount = await dashboardPage.getEventCount();
        console.log('Dashboard event count:', dashboardEventCount);
    });
});