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

test('Complete login flow with OTP for guqo@mailinator.com', async ({ page }) => {
  console.log('\n🧪 Starting Complete Login Test\n');

  // Step 1: Navigate to login page
  console.log('Step 1: Navigate to login page');
  await page.goto('http://localhost:9000/en/login');
  await page.waitForLoadState('networkidle');
  await expect(page.locator('h2:has-text("Log in")')).toBeVisible();
  console.log('✅ Login page loaded\n');

  // Step 2: Fill in email
  console.log('Step 2: Fill in email: guqo@mailinator.com');
  const emailInput = page.locator('input[type="text"]').first();
  await emailInput.fill('guqo@mailinator.com');
  const emailValue = await emailInput.inputValue();
  expect(emailValue).toBe('guqo@mailinator.com');
  console.log('✅ Email filled\n');

  // Step 3: Click Send OTP button
  console.log('Step 3: Click Send OTP button');
  const sendButton = page.locator('button:has-text("Send OTP")').first();
  await expect(sendButton).toBeVisible();

  // Listen for the API response
  const responsePromise = page.waitForResponse(
    response => response.url().includes('/api/auth/login') && response.request().method() === 'POST'
  );

  await sendButton.click();

  const response = await responsePromise;
  const responseData = await response.json();

  console.log('API Response:', {
    status: response.status(),
    success: responseData.success,
    requiresOTP: responseData.requiresOTP,
    hasCode: !!responseData.code,
  });

  expect(response.status()).toBe(200);
  expect(responseData.success).toBe(true);
  expect(responseData.requiresOTP).toBe(true);
  console.log('✅ OTP request successful\n');

  // Step 4: Verify OTP screen appears
  console.log('Step 4: Wait for OTP input screen');
  await page.waitForTimeout(1000);

  const otpInput = page.locator('input[maxlength="6"]');
  await expect(otpInput).toBeVisible({ timeout: 5000 });
  console.log('✅ OTP input screen appeared\n');

  // Step 5: Get OTP from response (dev mode) or MailHog
  const otpCode = responseData.code;
  console.log(`Step 5: OTP Code: ${otpCode}`);

  if (!otpCode) {
    // Try to get from MailHog
    console.log('OTP not in response, checking MailHog...');
    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto('http://localhost:8025');
    await mailhogPage.waitForTimeout(2000);

    // Look for latest email
    const latestEmail = mailhogPage.locator('.messages .msglist-message').first();
    if (await latestEmail.count() > 0) {
      await latestEmail.click();
      await mailhogPage.waitForTimeout(1000);

      // Extract OTP from email content
      const emailBody = await mailhogPage.locator('#preview-html, #preview-plain').textContent();
      const otpMatch = emailBody?.match(/\b\d{6}\b/);

      if (otpMatch) {
        console.log(`✅ Found OTP in MailHog: ${otpMatch[0]}`);
        await mailhogPage.close();
      } else {
        console.log('❌ Could not extract OTP from email');
        await mailhogPage.close();
        throw new Error('OTP not found in email');
      }
    } else {
      await mailhogPage.close();
      throw new Error('No emails in MailHog');
    }
  } else {
    console.log('✅ OTP code retrieved from dev response\n');
  }

  // Step 6: Enter OTP
  console.log('Step 6: Enter OTP code');
  await otpInput.fill(otpCode);
  const otpValue = await otpInput.inputValue();
  expect(otpValue).toBe(otpCode);
  console.log('✅ OTP entered\n');

  // Step 7: Click Verify button
  console.log('Step 7: Click Verify button');
  const verifyButton = page.locator('button:has-text("Verify")').first();
  await expect(verifyButton).toBeEnabled();

  const verifyResponsePromise = page.waitForResponse(
    response => response.url().includes('/api/auth/verify-login-otp') && response.request().method() === 'POST'
  );

  await verifyButton.click();

  const verifyResponse = await verifyResponsePromise;
  const verifyData = await verifyResponse.json();

  console.log('Verify Response:', {
    status: verifyResponse.status(),
    success: verifyData.success,
  });

  expect(verifyResponse.status()).toBe(200);
  console.log('✅ OTP verification successful\n');

  // Step 8: Wait for redirect to dashboard
  console.log('Step 8: Wait for redirect to dashboard');
  await page.waitForURL('**/dashboard', { timeout: 10000 });

  const currentUrl = page.url();
  console.log('Current URL:', currentUrl);
  expect(currentUrl).toContain('/dashboard');
  console.log('✅ Redirected to dashboard\n');

  // Step 9: Verify dashboard loaded
  console.log('Step 9: Verify dashboard content');
  await page.waitForTimeout(2000);

  // Check for dashboard elements
  const dashboardTitle = page.locator('h1, h2').filter({ hasText: /Dashboard|Welcome/i }).first();
  const hasDashboardContent = await dashboardTitle.count() > 0;

  if (hasDashboardContent) {
    const titleText = await dashboardTitle.textContent();
    console.log(`✅ Dashboard loaded: "${titleText}"\n`);
  } else {
    console.log('⚠️  Dashboard content not immediately visible (may still be loading)\n');
  }

  // Take final screenshot
  await page.screenshot({ path: '/tmp/login-complete-dashboard.png' });
  console.log('Screenshot saved: /tmp/login-complete-dashboard.png');

  console.log('\n🎉 COMPLETE LOGIN TEST PASSED!\n');
  console.log('Summary:');
  console.log('  ✅ Login page loaded');
  console.log('  ✅ Email accepted');
  console.log('  ✅ OTP sent successfully');
  console.log('  ✅ OTP screen appeared');
  console.log('  ✅ OTP verified successfully');
  console.log('  ✅ Redirected to dashboard');
  console.log('  ✅ Dashboard loaded');
});
