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

test.describe('Staff Login Portal', () => {
  test.beforeEach(async ({ page }) => {
    // Navigate to staff login page
    await page.goto('http://localhost:9000/staff/login');
  });

  test('Staff login page loads correctly', async ({ page }) => {
    // Wait for page to load
    await page.waitForLoadState('networkidle');

    // Take snapshot of login page
    await page.screenshot({
      path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-login-page.png',
      fullPage: true
    });

    // Check page title
    await expect(page).toHaveTitle(/Staff Login|Mawidi/i);

    // Verify form elements exist
    const usernameField = page.locator('input[name="username"], input[type="text"]').first();
    const passwordField = page.locator('input[name="password"], input[type="password"]').first();
    const loginButton = page.locator('button[type="submit"], button:has-text("Login"), button:has-text("Sign in")').first();

    await expect(usernameField).toBeVisible();
    await expect(passwordField).toBeVisible();
    await expect(loginButton).toBeVisible();

    console.log('✓ Staff login page loaded successfully');
    console.log('✓ Username field present');
    console.log('✓ Password field present');
    console.log('✓ Login button present');
  });

  test('Staff login with valid credentials', async ({ page }) => {
    // Wait for page to load
    await page.waitForLoadState('networkidle');

    // Fill in login credentials
    const usernameField = page.locator('input[name="username"], input[type="text"]').first();
    const passwordField = page.locator('input[name="password"], input[type="password"]').first();
    const loginButton = page.locator('button[type="submit"], button:has-text("Login"), button:has-text("Sign in")').first();

    await usernameField.fill('asim');
    await passwordField.fill('AsimMawidi2025!');

    console.log('✓ Filled username: asim');
    console.log('✓ Filled password: ********');

    // Take screenshot before login
    await page.screenshot({
      path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-login-before-submit.png',
      fullPage: true
    });

    // Submit login form
    await loginButton.click();

    console.log('✓ Clicked login button');

    // Wait for navigation (either to dashboard or error state)
    try {
      await page.waitForURL('**/staff/dashboard**', { timeout: 10000 });
      console.log('✓ Redirected to staff dashboard');
    } catch (error) {
      // Check if still on login page (login failed)
      const currentUrl = page.url();
      console.log(`Current URL after login attempt: ${currentUrl}`);

      // Take screenshot of error state
      await page.screenshot({
        path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-login-error.png',
        fullPage: true
      });
    }

    // Take screenshot after login attempt
    await page.screenshot({
      path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-login-after-submit.png',
      fullPage: true
    });

    // Check if we're on the dashboard
    const currentUrl = page.url();
    if (currentUrl.includes('/staff/dashboard')) {
      console.log('✓ Successfully logged in and redirected to dashboard');

      // Verify dashboard elements
      await page.waitForLoadState('networkidle');

      // Check for common dashboard elements
      const dashboardHeader = page.locator('h1, h2').first();
      await expect(dashboardHeader).toBeVisible();

      console.log('✓ Dashboard loaded successfully');

      // Take screenshot of dashboard
      await page.screenshot({
        path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-dashboard.png',
        fullPage: true
      });
    } else {
      console.log('✗ Login failed or did not redirect to dashboard');
      console.log(`Current URL: ${currentUrl}`);
    }
  });

  test('Check staff dashboard navigation', async ({ page }) => {
    // Login first
    await page.waitForLoadState('networkidle');

    const usernameField = page.locator('input[name="username"], input[type="text"]').first();
    const passwordField = page.locator('input[name="password"], input[type="password"]').first();
    const loginButton = page.locator('button[type="submit"], button:has-text("Login"), button:has-text("Sign in")').first();

    await usernameField.fill('asim');
    await passwordField.fill('AsimMawidi2025!');
    await loginButton.click();

    // Wait for dashboard
    try {
      await page.waitForURL('**/staff/dashboard**', { timeout: 10000 });

      // Look for navigation menu
      const navLinks = page.locator('nav a, aside a, [role="navigation"] a');
      const navCount = await navLinks.count();

      console.log(`✓ Found ${navCount} navigation links`);

      // Try to identify common navigation items
      const commonNavItems = ['Users', 'Settings', 'Analytics', 'Reports', 'Logout', 'Dashboard'];
      for (const item of commonNavItems) {
        const link = page.locator(`a:has-text("${item}")`).first();
        if (await link.isVisible({ timeout: 1000 }).catch(() => false)) {
          console.log(`✓ Found navigation item: ${item}`);
        }
      }

      // Take screenshot of navigation
      await page.screenshot({
        path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-dashboard-navigation.png',
        fullPage: true
      });

    } catch (error) {
      console.log('✗ Could not access dashboard to check navigation');
    }
  });

  test('Check for security features', async ({ page }) => {
    await page.waitForLoadState('networkidle');

    // Try invalid login to test lockout behavior
    const usernameField = page.locator('input[name="username"], input[type="text"]').first();
    const passwordField = page.locator('input[name="password"], input[type="password"]').first();
    const loginButton = page.locator('button[type="submit"], button:has-text("Login"), button:has-text("Sign in")').first();

    // Test with invalid credentials
    await usernameField.fill('asim');
    await passwordField.fill('WrongPassword123!');
    await loginButton.click();

    // Wait a moment for error message
    await page.waitForTimeout(2000);

    // Check for error message
    const errorMessage = page.locator('text=/invalid|error|incorrect|failed/i').first();
    const hasError = await errorMessage.isVisible({ timeout: 2000 }).catch(() => false);

    if (hasError) {
      console.log('✓ Error message displayed for invalid credentials');
      const errorText = await errorMessage.textContent();
      console.log(`  Error message: ${errorText}`);
    } else {
      console.log('⚠ No error message visible for invalid credentials');
    }

    // Take screenshot of error state
    await page.screenshot({
      path: '/Users/Asim/Desktop/mawidi_codex/mawidi-site/test-results/staff-login-invalid-credentials.png',
      fullPage: true
    });

    // Check if form is disabled (rate limiting)
    const isButtonDisabled = await loginButton.isDisabled({ timeout: 1000 }).catch(() => false);
    if (isButtonDisabled) {
      console.log('✓ Login button disabled after failed attempt (rate limiting active)');
    } else {
      console.log('⚠ Login button still enabled after failed attempt');
    }
  });

  test('Check page styling and branding', async ({ page }) => {
    await page.waitForLoadState('networkidle');

    // Check for logo or branding
    const logo = page.locator('img[alt*="Mawidi"], img[alt*="Logo"], svg[class*="logo"]').first();
    const hasLogo = await logo.isVisible({ timeout: 2000 }).catch(() => false);

    if (hasLogo) {
      console.log('✓ Logo/branding visible on login page');
    } else {
      console.log('⚠ No logo/branding found on login page');
    }

    // Check for page heading
    const heading = page.locator('h1, h2').first();
    const hasHeading = await heading.isVisible({ timeout: 2000 }).catch(() => false);

    if (hasHeading) {
      const headingText = await heading.textContent();
      console.log(`✓ Page heading: ${headingText}`);
    }

    // Check color scheme (look for dark/light theme indicators)
    const bodyBg = await page.locator('body').evaluate(el => {
      return window.getComputedStyle(el).backgroundColor;
    });
    console.log(`✓ Page background color: ${bodyBg}`);

    // Check if form is centered/styled properly
    const form = page.locator('form').first();
    if (await form.isVisible({ timeout: 2000 }).catch(() => false)) {
      const formBox = await form.boundingBox();
      if (formBox) {
        console.log(`✓ Form dimensions: ${formBox.width}x${formBox.height}`);
      }
    }
  });
});
