import { test, expect } from '@playwright/test';

test.describe('Trainer Registration', () => {
  test('should allow a new user to register as a trainer', async ({ page }) => {
    // Robust navigation and wait for form container
    console.log('Navigating to /trainer-registration/ ...');
    await page.goto('/trainer-registration/', { waitUntil: 'domcontentloaded', timeout: 30000 });
    await page.waitForTimeout(1000); // Give time for JS to initialize
    await page.screenshot({ path: 'registration-before-form-wait.png', fullPage: true });

    // Wait for the registration form container to be visible
    const formContainer = page.locator('.hvac-registration-form');
    await expect(formContainer).toBeVisible({ timeout: 30000 });
    console.log('Form container is visible.');
    await page.screenshot({ path: 'registration-form-container-visible.png', fullPage: true });

    // Wait for the actual form element to be visible and enabled
    const formElement = page.locator('#hvac-trainer-registration-form');
    await expect(formElement).toBeVisible({ timeout: 20000 });
    await expect(formElement).toBeEnabled();
    console.log('Form element is visible and enabled.');
    await page.screenshot({ path: 'registration-form-element-visible.png', fullPage: true });

    // Log current URL and take a screenshot
    console.log('Navigated to:', page.url());
    await page.screenshot({ path: 'registration-page.png', fullPage: true });

    // Check if the email field is visible and enabled with increased timeout
    // Robust wait and debug for email field
    const emailField = page.locator('#user_email');
    try {
      await expect(emailField).toBeVisible({ timeout: 30000 });
      await expect(emailField).toBeEnabled();
      console.log('Found and enabled email field.');
      await page.screenshot({ path: 'registration-email-found.png', fullPage: true });
    } catch (err) {
      console.error('Email field not found or not enabled:', err);
      await page.screenshot({ path: 'registration-email-NOTFOUND.png', fullPage: true });
      const allInputs = await page.locator('input').allTextContents();
      console.log('All input fields on page:', allInputs);
      throw err;
    }

    // Fill in registration form fields
    const timestamp = Date.now();
    const email = `testuser_${timestamp}@example.com`;
    const password = 'TestPassword123!'; // Use a strong password for registration

    await emailField.fill(email);
    console.log(`Filled in email field with: ${email}`);

    // Robust wait and debug for password field
    const passwordField = page.locator('#user_pass');
    try {
      await expect(passwordField).toBeVisible({ timeout: 15000 });
      await passwordField.fill(password);
      console.log('Filled in password field.');
    } catch (err) {
      console.error('Password field not found:', err);
      await page.screenshot({ path: 'registration-password-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Robust wait and debug for confirm password field
    const confirmPasswordField = page.locator('#confirm_password');
    try {
      await expect(confirmPasswordField).toBeVisible({ timeout: 15000 });
      await confirmPasswordField.fill(password);
      console.log('Filled in confirm password field.');
    } catch (err) {
      console.error('Confirm password field not found:', err);
      await page.screenshot({ path: 'registration-confirm-password-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Fill in required personal information fields (based on page content)
    // Robust wait and debug for first name field
    const firstNameField = page.locator('#first_name');
    try {
      await expect(firstNameField).toBeVisible({ timeout: 15000 });
      await firstNameField.fill('Test');
      console.log('Filled in first name field.');
    } catch (err) {
      console.error('First name field not found:', err);
      await page.screenshot({ path: 'registration-first-name-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Robust wait and debug for last name field
    const lastNameField = page.locator('#last_name');
    try {
      await expect(lastNameField).toBeVisible({ timeout: 15000 });
      await lastNameField.fill('User');
      console.log('Filled in last name field.');
    } catch (err) {
      console.error('Last name field not found:', err);
      await page.screenshot({ path: 'registration-last-name-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Robust wait and debug for display name field
    const displayNameField = page.locator('#display_name');
    try {
      await expect(displayNameField).toBeVisible({ timeout: 15000 });
      await displayNameField.fill(`Test User ${timestamp}`);
      console.log('Filled in display name field.');
    } catch (err) {
      console.error('Display name field not found:', err);
      await page.screenshot({ path: 'registration-display-name-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Robust wait and debug for description field
    const descriptionField = page.locator('#description');
    try {
      await expect(descriptionField).toBeVisible({ timeout: 15000 });
      await descriptionField.fill('This is a test user bio.');
      console.log('Filled in biographical info field.');
    } catch (err) {
      console.error('Description field not found:', err);
      await page.screenshot({ path: 'registration-description-NOTFOUND.png', fullPage: true });
      throw err;
    }

    // Fill in required business information fields (based on page content)
    const businessNameField = page.locator('#business_name');
    await expect(businessNameField).toBeVisible();
    await businessNameField.fill(`Test Business ${timestamp}`);
    console.log('Filled in business name field.');

    const businessPhoneField = page.locator('#business_phone');
    await expect(businessPhoneField).toBeVisible();
    await businessPhoneField.fill('123-456-7890');
    console.log('Filled in business phone field.');

    const businessEmailField = page.locator('#business_email');
    await expect(businessEmailField).toBeVisible();
    await businessEmailField.fill(`business_${timestamp}@example.com`);
    console.log('Filled in business email field.');

    const businessDescriptionField = page.locator('#business_description');
    await expect(businessDescriptionField).toBeVisible();
    await businessDescriptionField.fill('This is a test business description.');
    console.log('Filled in business description field.');

    // Fill in required address information fields (based on page content)
    const countrySelect = page.locator('#user_country');
    await expect(countrySelect).toBeVisible();
    await countrySelect.selectOption('United States');
    console.log('Selected country.');

    // Wait for state/province field to become visible/enabled after selecting country
    const stateSelect = page.locator('#user_state');
    await expect(stateSelect).toBeVisible();
    await stateSelect.selectOption('California'); // Assuming California is an option for US
    console.log('Selected state/province.');

    const cityField = page.locator('#user_city');
    await expect(cityField).toBeVisible();
    await cityField.fill('Test City');
    console.log('Filled in city field.');

    const zipField = page.locator('#user_zip');
    await expect(zipField).toBeVisible();
    await zipField.fill('90210');
    console.log('Filled in zip/postal code field.');

    // Select "No" for creating a training venue profile (default is No, but explicitly select for clarity)
    const createVenueNoRadio = page.locator('input[name="create_venue"][value="No"]');
    await expect(createVenueNoRadio).toBeVisible();
    await createVenueNoRadio.check();
    console.log('Selected not to create training venue profile.');

    // Fill in required training information fields (based on page content)
    const businessTypeRadio = page.locator('input[name="business_type"][value="Educator"]'); // Assuming Educator is a valid type
    await expect(businessTypeRadio).toBeVisible();
    await businessTypeRadio.check();
    console.log('Selected business type.');

    const trainingAudienceCheckbox = page.locator('input[name="training_audience[]"][value="Industry professionals"]'); // Assuming this is a valid option
    await expect(trainingAudienceCheckbox).toBeVisible();
    await trainingAudienceCheckbox.check();
    console.log('Selected training audience.');

    const trainingFormatsCheckbox = page.locator('input[name="training_formats[]"][value="In-person"]'); // Assuming this is a valid option
    await expect(trainingFormatsCheckbox).toBeVisible();
    await trainingFormatsCheckbox.check();
    console.log('Selected training format.');

    const trainingLocationsCheckbox = page.locator('input[name="training_locations[]"][value="Local"]'); // Assuming this is a valid option
    await expect(trainingLocationsCheckbox).toBeVisible();
    await trainingLocationsCheckbox.check();
    console.log('Selected training location.');

    const trainingResourcesCheckbox = page.locator('input[name="training_resources[]"][value="Classroom"]'); // Assuming this is a valid option
    await expect(trainingResourcesCheckbox).toBeVisible();
    await trainingResourcesCheckbox.check();
    console.log('Selected training resource.');

    // Fill in required application details field (based on page content)
    const applicationDetailsField = page.locator('#application_details');
    await expect(applicationDetailsField).toBeVisible();
    await applicationDetailsField.fill('Applying to become a trainer for testing purposes.');
    console.log('Filled in application details.');


    // Click the Register button
    const registerButton = page.locator('input[type="submit"][name="hvac_register"]');
    await expect(registerButton).toBeVisible();
    await registerButton.click();
    console.log('Clicked Register button.');

    // TODO: Add assertions for successful registration (e.g., check for success message or redirect)
    // For now, just wait for navigation or a few seconds to see what happens
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(5000); // Wait for 5 seconds to observe result

    console.log('Final URL:', page.url());
    await page.screenshot({ path: 'registration-after-submit.png', fullPage: true });

    // Basic assertion: Check if the URL is NOT the error URL
    expect(page.url()).not.toContain('reg_error=1');
  });
});
