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

// Manual certificate management test
// To run this test manually:
// 1. Ensure certificates have been generated for some events
// 2. Run this test with:
//    npx playwright test tests/e2e/certificate-management-manual.test.ts

test('should verify certificate management functionality', async ({ page }) => {
  const stagingUrl = process.env.UPSKILL_STAGING_URL || 'https://wordpress-974670-5399585.cloudwaysapps.com';
  
  console.log('Step 1: Logging in...');
  // Navigate to login page
  await page.goto(`${stagingUrl}/community-login/`);

  // Login as trainer
  await page.fill('#user_login', 'test_trainer');
  await page.fill('#user_pass', 'Test123!');
  await page.click('#wp-submit');
  await page.waitForLoadState('networkidle');
  
  // Verify successful login by checking URL
  const url = page.url();
  expect(url).toContain('hvac-dashboard');
  
  console.log('Step 2: Navigate to Certificate Reports...');
  // Navigate to the certificate reports page
  await page.goto(`${stagingUrl}/certificate-reports/`);
  await page.waitForLoadState('networkidle');
  
  // Take a screenshot to verify the page loaded
  await page.screenshot({ path: 'certificate-reports-page.png' });
  
  console.log('Step 3: Checking for certificate reports UI elements...');
  // Check for page title
  const pageTitle = page.locator('h1:has-text("Certificate Reports"), h1:has-text("Certificates")');
  await expect(pageTitle).toBeVisible();
  
  // Check for certificate table
  const certificateTable = page.locator('table.hvac-certificate-table, table.certificate-table');
  
  if (await certificateTable.isVisible()) {
    // Check if there are any certificates
    const tableRows = certificateTable.locator('tbody tr');
    const rowCount = await tableRows.count();
    
    console.log(`Found ${rowCount} certificates in the table`);
    
    if (rowCount > 0) {
      // Test viewing a certificate
      console.log('Step 4a: Testing certificate viewing functionality...');
      const viewButton = page.locator('button:has-text("View"), a:has-text("View")').first();
      
      if (await viewButton.isVisible()) {
        await viewButton.click();
        await page.waitForTimeout(2000);
        await page.screenshot({ path: 'view-certificate.png' });
        
        // Check for certificate preview or PDF
        const certificatePreview = page.locator('.certificate-preview, iframe');
        const certificateModal = page.locator('.modal, .certificate-modal');
        
        if (await certificatePreview.isVisible() || await certificateModal.isVisible()) {
          console.log('Certificate preview is visible');
          
          // Close preview if there's a close button
          const closeButton = page.locator('button:has-text("Close"), .close-button, .modal-close');
          if (await closeButton.isVisible()) {
            await closeButton.click();
            await page.waitForTimeout(1000);
          }
        } else {
          console.log('No certificate preview found - it might open in a new tab or download');
        }
      } else {
        console.log('No View button found for certificates');
      }
      
      // Test email functionality if available
      console.log('Step 4b: Testing certificate email functionality...');
      const emailButton = page.locator('button:has-text("Email"), a:has-text("Email")').first();
      
      if (await emailButton.isVisible()) {
        await emailButton.click();
        await page.waitForTimeout(2000);
        await page.screenshot({ path: 'email-certificate.png' });
        
        // Check for email confirmation dialog
        const confirmEmailButton = page.locator('button:has-text("Send"), button:has-text("Confirm")');
        if (await confirmEmailButton.isVisible()) {
          await confirmEmailButton.click();
          await page.waitForTimeout(2000);
          
          // Check for success message
          const successMessage = page.locator('.success-message, .hvac-success-message');
          if (await successMessage.isVisible()) {
            const message = await successMessage.textContent();
            console.log(`Email success message: ${message}`);
          }
        }
      } else {
        console.log('No Email button found for certificates');
      }
      
      // Test revocation functionality if there are multiple certificates
      if (rowCount > 1) {
        console.log('Step 4c: Testing certificate revocation functionality...');
        const revokeButton = page.locator('button:has-text("Revoke"), a:has-text("Revoke")').nth(1);
        
        if (await revokeButton.isVisible()) {
          await revokeButton.click();
          await page.waitForTimeout(2000);
          await page.screenshot({ path: 'revoke-certificate.png' });
          
          // Check for revocation confirmation dialog
          const confirmRevokeButton = page.locator('button:has-text("Confirm Revocation"), button:has-text("Confirm")');
          if (await confirmRevokeButton.isVisible()) {
            await confirmRevokeButton.click();
            await page.waitForTimeout(2000);
            
            // Check for success message
            const successMessage = page.locator('.success-message, .hvac-success-message');
            if (await successMessage.isVisible()) {
              const message = await successMessage.textContent();
              console.log(`Revocation success message: ${message}`);
            }
            
            // Refresh the page to see updated status
            await page.goto(`${stagingUrl}/certificate-reports/`);
            await page.waitForLoadState('networkidle');
          }
        } else {
          console.log('No Revoke button found for certificates');
        }
      }
      
      // Test pagination if available
      console.log('Step 4d: Testing pagination functionality...');
      const paginationControls = page.locator('.pagination, .paging-nav, .hvac-pagination');
      
      if (await paginationControls.isVisible()) {
        console.log('Pagination controls are visible');
        
        // Try to go to next page
        const nextButton = page.locator('a:has-text("Next"), .next-page, .pagination-next');
        if (await nextButton.isVisible() && !(await nextButton.isDisabled())) {
          await nextButton.click();
          await page.waitForTimeout(2000);
          await page.screenshot({ path: 'pagination-next.png' });
          
          // Try to go back to previous page
          const prevButton = page.locator('a:has-text("Previous"), .prev-page, .pagination-prev');
          if (await prevButton.isVisible() && !(await prevButton.isDisabled())) {
            await prevButton.click();
            await page.waitForTimeout(2000);
            await page.screenshot({ path: 'pagination-prev.png' });
          }
        } else {
          console.log('Next page button not available or disabled');
        }
      } else {
        console.log('No pagination controls found');
      }
    } else {
      console.log('No certificates found in the table. Generate certificates first and then run this test.');
    }
  } else {
    console.log('Certificate table not found. The page structure may be different than expected.');
    
    // Take a screenshot of the full page for debugging
    await page.screenshot({ path: 'certificate-reports-full.png', fullPage: true });
  }
  
  console.log('Certificate management test completed');
});