/**
 * User Profile Edit Test
 * 
 * Tags: @user @p2 @profile
 * 
 * Tests user profile management:
 * - View profile page
 * - View profile details
 * - Edit profile (if editable)
 * - Profile information display
 * - Profile navigation
 */

import { test, expect } from '@playwright/test';
import { 
  printTestCase, 
  printSuccess, 
  printWarning, 
  ensureAuthenticated 
} from '../../helpers/test-helpers';

test.describe('03_User_Management - User Profile Edit', () => {
  test.use({ storageState: 'auth.json' });
  
  test.beforeEach(async ({ page }) => {
    await ensureAuthenticated(page);
  });
  
  test('Test Case 1: Navigate to user profile', async ({ page }) => {
    printTestCase(1, 'Navigate to User Profile');
    
    await page.goto('/');
    await page.waitForLoadState('load');
    
    // Look for user profile link in header
    const profileLink = page.locator('a[href*="userprofile"], a:has-text("Profile")');
    
    if (await profileLink.isVisible().catch(() => false)) {
      await profileLink.click();
      await page.waitForTimeout(1000);
      printSuccess('Profile link clicked');
    } else {
      // Try navigating directly
      await page.goto('/users/userprofile');
      await page.waitForTimeout(1000);
      printSuccess('Navigated directly to profile page');
    }
    
    // Verify we're on the profile page
    const currentUrl = page.url();
    if (currentUrl.includes('userprofile') || currentUrl.includes('profile')) {
      printSuccess(`Profile page loaded: ${currentUrl}`);
    } else {
      printWarning('Profile page URL not as expected');
    }
  });
  
  test('Test Case 2: View profile information', async ({ page }) => {
    printTestCase(2, 'View Profile Information');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    await page.waitForTimeout(1000);
    
    // Look for profile information fields
    const profileFields = [
      { label: 'Name', selector: 'input[name="fullname"], #fullname, [placeholder*="name" i]' },
      { label: 'Email', selector: 'input[name="email"], #email, input[type="email"]' },
      { label: 'Phone', selector: 'input[name="phone"], #phone, input[type="tel"]' },
      { label: 'Username', selector: 'input[name="username"], #username' }
    ];
    
    let foundFields = 0;
    
    for (const field of profileFields) {
      const fieldElement = page.locator(field.selector).first();
      if (await fieldElement.isVisible().catch(() => false)) {
        const value = await fieldElement.inputValue().catch(() => '');
        printSuccess(`${field.label} field found${value ? `: ${value}` : ''}`);
        foundFields++;
      }
    }
    
    if (foundFields > 0) {
      printSuccess(`Found ${foundFields} profile fields`);
    } else {
      printWarning('No profile fields found - may be display-only');
      
      // Check for display elements
      const profileInfo = page.locator('.profile-info, .user-details, .card-body');
      if (await profileInfo.isVisible().catch(() => false)) {
        const infoText = await profileInfo.textContent();
        printSuccess('Profile information displayed');
      }
    }
  });
  
  test('Test Case 3: Check profile image', async ({ page }) => {
    printTestCase(3, 'Check Profile Image');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for profile image
    const profileImage = page.locator('img.profile-pic, img.avatar, img[alt*="profile" i], img[alt*="user" i]').first();
    
    if (await profileImage.isVisible().catch(() => false)) {
      printSuccess('Profile image found');
      
      // Check if image has valid src
      const src = await profileImage.getAttribute('src');
      if (src && src.length > 0) {
        printSuccess(`Profile image src: ${src.substring(0, 50)}...`);
      }
      
      // Check for upload/change image button
      const changeImageBtn = page.locator('button:has-text("Change"), button:has-text("Upload"), input[type="file"]');
      if (await changeImageBtn.isVisible().catch(() => false)) {
        printSuccess('Change profile image option available');
      }
    } else {
      printWarning('Profile image not found');
    }
  });
  
  test('Test Case 4: Test edit profile functionality', async ({ page }) => {
    printTestCase(4, 'Test Edit Profile Functionality');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    await page.waitForTimeout(1000);
    
    // Look for edit button or editable fields
    const editBtn = page.locator('button:has-text("Edit"), button:has-text("Update"), #editProfileBtn');
    
    if (await editBtn.isVisible().catch(() => false)) {
      printSuccess('Edit profile button found');
      
      await editBtn.click();
      await page.waitForTimeout(500);
      printSuccess('Edit mode activated');
      
      // Check if fields become editable
      const nameInput = page.locator('input[name="fullname"], #fullname').first();
      if (await nameInput.isVisible().catch(() => false)) {
        const isDisabled = await nameInput.isDisabled();
        if (!isDisabled) {
          printSuccess('Profile fields are editable');
          
          // Try editing (but don't save)
          const originalValue = await nameInput.inputValue();
          await nameInput.fill(originalValue + ' '); // Add space
          printSuccess('Test edit made (not saving)');
          
          // Restore original value
          await nameInput.fill(originalValue);
          printSuccess('Original value restored');
        } else {
          printWarning('Fields appear disabled');
        }
      }
    } else {
      // Check if fields are always editable
      const nameInput = page.locator('input[name="fullname"], #fullname').first();
      if (await nameInput.isVisible().catch(() => false)) {
        const isDisabled = await nameInput.isDisabled();
        if (!isDisabled) {
          printSuccess('Profile fields are editable (no edit button needed)');
        } else {
          printWarning('Profile may be view-only');
        }
      } else {
        printWarning('Edit functionality not found');
      }
    }
  });
  
  test('Test Case 5: Check for save/update button', async ({ page }) => {
    printTestCase(5, 'Check for Save/Update Button');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for save/update button
    const saveBtn = page.locator('button:has-text("Save"), button:has-text("Update"), button[type="submit"], #saveProfileBtn');
    
    if (await saveBtn.isVisible().catch(() => false)) {
      printSuccess('Save/Update button found');
      
      // Check if button is enabled
      const isEnabled = await saveBtn.isEnabled();
      if (isEnabled) {
        printSuccess('Save button is enabled');
      } else {
        printWarning('Save button is disabled');
      }
    } else {
      printWarning('Save button not found - may auto-save or be view-only');
    }
  });
  
  test('Test Case 6: Check profile sections', async ({ page }) => {
    printTestCase(6, 'Check Profile Sections');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for common profile sections
    const sections = [
      { name: 'Personal Information', selector: '.personal-info, h3:has-text("Personal"), h4:has-text("Personal")' },
      { name: 'Contact Information', selector: '.contact-info, h3:has-text("Contact"), h4:has-text("Contact")' },
      { name: 'Account Settings', selector: '.account-settings, h3:has-text("Account"), h4:has-text("Account")' },
      { name: 'Security', selector: '.security, h3:has-text("Security"), h4:has-text("Password")' }
    ];
    
    let foundSections = 0;
    
    for (const section of sections) {
      const sectionElement = page.locator(section.selector).first();
      if (await sectionElement.isVisible().catch(() => false)) {
        printSuccess(`${section.name} section found`);
        foundSections++;
      }
    }
    
    if (foundSections > 0) {
      printSuccess(`Found ${foundSections} profile sections`);
    } else {
      printWarning('Profile sections not clearly identified');
    }
  });
  
  test('Test Case 7: Check password change functionality', async ({ page }) => {
    printTestCase(7, 'Check Password Change Functionality');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for password change section or button
    const changePasswordBtn = page.locator('button:has-text("Change Password"), a:has-text("Change Password"), #changePasswordBtn');
    
    if (await changePasswordBtn.isVisible().catch(() => false)) {
      printSuccess('Change password option found');
      
      await changePasswordBtn.click();
      await page.waitForTimeout(1000);
      
      // Check for password fields
      const currentPasswordInput = page.locator('input[name="current_password"], #current_password, input[placeholder*="current" i]');
      const newPasswordInput = page.locator('input[name="new_password"], #new_password, input[placeholder*="new" i]');
      
      const hasCurrentPassword = await currentPasswordInput.isVisible().catch(() => false);
      const hasNewPassword = await newPasswordInput.isVisible().catch(() => false);
      
      if (hasCurrentPassword && hasNewPassword) {
        printSuccess('Password change fields found');
        
        // Don't actually change password - just verify UI
        printSuccess('Password change UI verified (not testing actual change)');
      } else {
        printWarning('Password change fields not found');
      }
    } else {
      printWarning('Password change option not found');
    }
  });
  
  test('Test Case 8: Verify profile breadcrumbs/navigation', async ({ page }) => {
    printTestCase(8, 'Verify Profile Breadcrumbs/Navigation');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for breadcrumbs
    const breadcrumbs = page.locator('.breadcrumb, nav[aria-label="breadcrumb"]');
    
    if (await breadcrumbs.isVisible().catch(() => false)) {
      const breadcrumbText = await breadcrumbs.textContent();
      printSuccess(`Breadcrumbs found: ${breadcrumbText}`);
    } else {
      printWarning('Breadcrumbs not found');
    }
    
    // Look for back button
    const backBtn = page.locator('button:has-text("Back"), a:has-text("Back"), .back-button');
    
    if (await backBtn.isVisible().catch(() => false)) {
      printSuccess('Back button found');
    } else {
      printWarning('Back button not found');
    }
  });
  
  test('Test Case 9: Check for role/permissions display', async ({ page }) => {
    printTestCase(9, 'Check for Role/Permissions Display');
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    
    // Look for role information
    const roleElement = page.locator('text=/role/i, .user-role, [class*="role"]');
    
    if (await roleElement.isVisible().catch(() => false)) {
      const roleText = await roleElement.textContent();
      printSuccess(`Role information found: ${roleText}`);
    } else {
      printWarning('Role information not displayed');
    }
    
    // Look for store information
    const storeElement = page.locator('text=/store/i, .user-store, [class*="store"]');
    
    if (await storeElement.isVisible().catch(() => false)) {
      const storeText = await storeElement.textContent();
      printSuccess(`Store information found: ${storeText}`);
    } else {
      printWarning('Store information not displayed');
    }
  });
  
  test('Test Case 10: Verify profile page loads without errors', async ({ page }) => {
    printTestCase(10, 'Verify Profile Page Loads Without Errors');
    
    // Listen for console errors
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });
    
    await page.goto('/users/userprofile');
    await page.waitForLoadState('load');
    await page.waitForTimeout(2000);
    
    // Verify page loaded
    const pageTitle = await page.title();
    printSuccess(`Page title: ${pageTitle}`);
    
    // Check for console errors
    if (errors.length === 0) {
      printSuccess('No console errors detected');
    } else {
      printWarning(`Console errors detected: ${errors.length}`);
    }
    
    // Verify page has content
    const bodyText = await page.locator('body').textContent();
    if (bodyText && bodyText.length > 100) {
      printSuccess('Page has content');
    } else {
      printWarning('Page appears empty');
    }
  });
});

