/**
 * E2E Tests for Complete Billing Management Flow
 * Tests viewing current plan, upgrading/downgrading, and viewing invoices
 */

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

const TEST_USER = {
  email: 'guqo@mailinator.com',
  // OTP will be fetched from MailHog
};

const MAILHOG_URL = 'http://localhost:8025';

test.describe('Billing Management - Complete Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Navigate to login
    await page.goto('http://localhost:9000/en/login');

    // Enter email
    await page.fill('input[type="email"]', TEST_USER.email);
    await page.click('button[type="submit"]');

    // Wait for OTP form
    await page.waitForSelector('input[inputmode="numeric"]', { timeout: 10000 });

    // Fetch OTP from MailHog
    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto(MAILHOG_URL);
    await mailhogPage.waitForTimeout(2000);

    // Find latest email
    const emailFrame = mailhogPage.frameLocator('iframe[name="preview-html"]');
    const otpText = await emailFrame.locator('body').textContent();
    const otpMatch = otpText?.match(/\b\d{6}\b/);

    await mailhogPage.close();

    if (!otpMatch) {
      throw new Error('Could not find OTP in email');
    }

    const otp = otpMatch[0];

    // Enter OTP
    const otpInputs = await page.locator('input[inputmode="numeric"]').all();
    for (let i = 0; i < otp.length; i++) {
      await otpInputs[i].fill(otp[i]);
    }

    // Wait for redirect to dashboard
    await page.waitForURL(/\/dashboard/, { timeout: 15000 });
  });

  test('should view current plan details', async ({ page }) => {
    // Navigate to billing page
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Wait for current plan to load
    await expect(page.locator('h2:has-text("Your Current Plan")')).toBeVisible();

    // Check for plan details
    const planCard = page.locator('div').filter({ hasText: /Current Plan/i }).first();
    await expect(planCard).toBeVisible();

    // Should show plan name (Starter, Professional, or Enterprise)
    await expect(planCard.locator('text=/Starter|Professional|Enterprise/')).toBeVisible();

    // Should show monthly price
    await expect(planCard.locator('text=/\\$\\d+/')).toBeVisible();

    // Should show billing cycle progress
    await expect(planCard.locator('text=/days remaining/')).toBeVisible();

    // Should show features
    await expect(planCard.locator('text=/WhatsApp/')).toBeVisible();
  });

  test('should show upgrade options with proration', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Wait for plan options section
    await expect(page.locator('h2:has-text("Change Your Plan")')).toBeVisible();

    // Check for upgrade options (assuming user is on Starter)
    const upgradeSection = page.locator('h3:has-text("Upgrade Options")').locator('..');

    if (await upgradeSection.isVisible()) {
      // Should show Professional and/or Enterprise
      const planOptions = upgradeSection.locator('div').filter({ hasText: /Professional|Enterprise/ });
      await expect(planOptions.first()).toBeVisible();

      // Each option should show proration details
      await expect(upgradeSection.locator('text=/Credit from current plan/')).toBeVisible();
      await expect(upgradeSection.locator('text=/Immediate Charge/')).toBeVisible();
      await expect(upgradeSection.locator('text=/Next billing/')).toBeVisible();

      // Should have upgrade button
      await expect(upgradeSection.locator('button:has-text("Upgrade")')).toBeVisible();
    }
  });

  test('should show downgrade options if applicable', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Check for downgrade section (only if user is on Professional or Enterprise)
    const downgradeSection = page.locator('h3:has-text("Downgrade Options")');

    if (await downgradeSection.isVisible()) {
      const container = downgradeSection.locator('..');

      // Should show downgrade button
      await expect(container.locator('button:has-text("Downgrade")')).toBeVisible();

      // Should show credit will be applied
      await expect(container.locator('text=/credit/')).toBeVisible();
    }
  });

  test('should display invoices with download links', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Wait for invoices section
    await expect(page.locator('h2:has-text("Invoices")')).toBeVisible();

    // Check payment summary
    const summaryCard = page.locator('h3:has-text("Payment Summary")').locator('..');
    await expect(summaryCard).toBeVisible();
    await expect(summaryCard.locator('text=/Total Paid/')).toBeVisible();
    await expect(summaryCard.locator('text=/\\$\\d+\\.\\d{2}/')).toBeVisible();

    // Check for invoice list
    const invoicesSection = page.locator('h3:has-text("📄 Invoices")').locator('..');

    // If user has invoices
    const firstInvoice = invoicesSection.locator('div').filter({ hasText: /#INV-|#in_/ }).first();

    if (await firstInvoice.isVisible()) {
      // Should show invoice number
      await expect(firstInvoice.locator('text=/#|INV-/')).toBeVisible();

      // Should show amount
      await expect(firstInvoice.locator('text=/\\$\\d+\\.\\d{2}/')).toBeVisible();

      // Should show status badge (Paid, Open, etc.)
      await expect(firstInvoice.locator('text=/Paid|Open|Void/')).toBeVisible();

      // Should have PDF download link
      const pdfLink = firstInvoice.locator('a:has-text("Download PDF")');
      if (await pdfLink.isVisible()) {
        expect(await pdfLink.getAttribute('href')).toMatch(/stripe\.com|pay\.stripe\.com/);
      }
    } else {
      // No invoices yet - should show empty state
      await expect(invoicesSection.locator('text=/No invoices yet/')).toBeVisible();
    }
  });

  test('should handle plan upgrade flow (modal test only)', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Wait for page to load
    await page.waitForLoadState('networkidle');

    // Find and click upgrade button
    const upgradeButton = page.locator('button:has-text("Upgrade")').first();

    if (await upgradeButton.isVisible()) {
      await upgradeButton.click();

      // Should show confirmation modal
      await expect(page.locator('text=/Confirm Upgrade/')).toBeVisible({ timeout: 5000 });

      // Modal should show proration breakdown
      await expect(page.locator('text=/Charge Breakdown/')).toBeVisible();
      await expect(page.locator('text=/Credit from current plan/')).toBeVisible();
      await expect(page.locator('text=/Total Today/')).toBeVisible();

      // Should have confirm and cancel buttons
      await expect(page.locator('button:has-text("Confirm")')).toBeVisible();
      await expect(page.locator('button:has-text("Cancel")')).toBeVisible();

      // Click cancel to close modal (don't actually upgrade)
      await page.locator('button:has-text("Cancel")').click();

      // Modal should close
      await expect(page.locator('text=/Confirm Upgrade/')).not.toBeVisible({ timeout: 2000 });
    }
  });

  test('should show all three sections simultaneously', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // All three main sections should be visible
    await expect(page.locator('h2:has-text("Your Current Plan")')).toBeVisible();
    await expect(page.locator('h2:has-text("Change Your Plan")')).toBeVisible();
    await expect(page.locator('h2:has-text("Invoices")')).toBeVisible();

    // Quick actions should be visible
    await expect(page.locator('h3:has-text("Quick Actions")')).toBeVisible();

    // Help section should be at bottom
    await expect(page.locator('h3:has-text("Need Help?")')).toBeVisible();
  });

  test('should handle navigation correctly', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Back to dashboard link
    const backLink = page.locator('a:has-text("Dashboard")');
    await expect(backLink).toBeVisible();
    expect(await backLink.getAttribute('href')).toBe('/en/dashboard');

    // Compare plans link
    const comparePlansLink = page.locator('a:has-text("Compare")').first();
    await expect(comparePlansLink).toBeVisible();
    expect(await comparePlansLink.getAttribute('href')).toContain('/pricing');

    // Contact support link
    const contactLink = page.locator('a:has-text("Contact Support")');
    await expect(contactLink).toBeVisible();
    expect(await contactLink.getAttribute('href')).toContain('/contact');
  });

  test('should be responsive on mobile', async ({ page }) => {
    await page.setViewportSize({ width: 375, height: 667 });
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // All sections should be visible on mobile
    await expect(page.locator('h2:has-text("Your Current Plan")')).toBeVisible();
    await expect(page.locator('h2:has-text("Change Your Plan")')).toBeVisible();
    await expect(page.locator('h2:has-text("Invoices")')).toBeVisible();

    // Content should not overflow
    const body = page.locator('body');
    const scrollWidth = await body.evaluate((el) => el.scrollWidth);
    const clientWidth = await body.evaluate((el) => el.clientWidth);

    expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 20); // Allow small margin
  });

  test('should handle Arabic (RTL) layout', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard/billing-new');

    // Check RTL direction
    const main = page.locator('main');
    await expect(main).toHaveAttribute('dir', 'rtl');

    // Arabic text should be visible
    await expect(page.locator('text=/خطتك الحالية/')).toBeVisible();
    await expect(page.locator('text=/الفواتير/')).toBeVisible();

    // Navigation should work
    await expect(page.locator('a:has-text("لوحة التحكم")')).toBeVisible();
  });
});

test.describe('Invoice Actions', () => {
  test.beforeEach(async ({ page }) => {
    // Quick login (assumes test data exists)
    await page.goto('http://localhost:9000/en/login');
    // ... login flow ...
  });

  test('should open PDF in new tab', async ({ page, context }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Find PDF download link
    const pdfLink = page.locator('a:has-text("Download PDF")').first();

    if (await pdfLink.isVisible()) {
      // Get href before clicking
      const pdfUrl = await pdfLink.getAttribute('href');
      expect(pdfUrl).toMatch(/stripe\.com|pay\.stripe\.com/);

      // Verify target blank
      expect(await pdfLink.getAttribute('target')).toBe('_blank');
      expect(await pdfLink.getAttribute('rel')).toContain('noopener');
    }
  });

  test('should show "Pay Now" button for open invoices', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard/billing-new');

    // Check for any open invoices
    const openInvoice = page.locator('span:has-text("Open")').locator('..');

    if (await openInvoice.isVisible()) {
      // Should have "Pay Now" button
      await expect(openInvoice.locator('button:has-text("Pay Now")')).toBeVisible();
    }
  });
});
