/**
 * E2E Test: Complete Billing Flow
 * Tests the user journey from dashboard to billing management
 *
 * User Flow:
 * 1. Login to dashboard
 * 2. Click "My Account" → Settings modal opens
 * 3. Navigate to Billing tab
 * 4. View current plan details
 * 5. Click "Upgrade Plan" button
 * 6. View invoices
 * 7. Download invoice PDF
 */

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

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

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

  test('should complete full billing flow via My Account', async ({ page }) => {
    // Step 1: Login
    await page.goto('http://localhost:9000/en/login');
    await page.fill('input[type="email"]', TEST_USER.email);
    await page.click('button[type="submit"]');

    // Wait for OTP page
    await expect(page).toHaveURL(/.*verify-login-otp.*/);

    // Get OTP from MailHog (assuming it's running)
    // Note: In real test, fetch from http://localhost:8025/api/v2/messages
    // For now, we'll skip actual OTP entry and test the UI flow

    // MOCK: Assume we're logged in - navigate directly to dashboard
    await page.goto('http://localhost:9000/en/dashboard');

    // Step 2: Wait for dashboard to load
    await expect(page.locator('text=Welcome back')).toBeVisible({ timeout: 10000 });

    // Step 3: Click on user avatar to open AccountDropdown
    const avatarButton = page.locator('button:has-text("User"), button:has(div[class*="rounded-full"])').first();
    await avatarButton.click();

    // Step 4: Verify dropdown menu is visible
    await expect(page.locator('text=My Account')).toBeVisible();
    await expect(page.locator('text=Billing')).toBeVisible();

    // Step 5: Click "My Account" to open settings modal
    await page.click('text=My Account');

    // Step 6: Verify AccountSettingsModal opened
    await expect(page.locator('text=Account Settings')).toBeVisible();

    // Step 7: Click on Billing tab
    await page.click('text=Billing');

    // Step 8: Verify billing content is displayed
    await expect(page.locator('text=Billing & Subscription')).toBeVisible();

    // Step 9: Check for current plan card (if user has subscription)
    const hasSubscription = await page.locator('text=Active Account').isVisible().catch(() => false);

    if (hasSubscription) {
      // Verify current plan details are shown
      await expect(page.locator('text=Active Account')).toBeVisible();

      // Verify upgrade button exists
      await expect(page.locator('button:has-text("Upgrade Plan")')).toBeVisible();

      // Step 10: Click "Upgrade Plan" button
      await page.click('button:has-text("Upgrade Plan")');

      // Verify upgrade modal opens
      await expect(page.locator('text=Upgrade Your Plan, text=Change Plan')).toBeVisible({ timeout: 5000 });

      // Close modal
      const closeButton = page.locator('button[aria-label="Close"], button:has(svg)').last();
      await closeButton.click();

      // Step 11: Verify invoices section
      await expect(page.locator('text=Invoices')).toBeVisible();

      // Check if invoices table is present
      const hasInvoices = await page.locator('table').isVisible().catch(() => false);

      if (hasInvoices) {
        // Verify invoice table headers
        await expect(page.locator('th:has-text("Invoice #")')).toBeVisible();
        await expect(page.locator('th:has-text("Date")')).toBeVisible();
        await expect(page.locator('th:has-text("Amount")')).toBeVisible();

        // Verify at least one invoice row
        const invoiceRows = page.locator('tbody tr');
        const rowCount = await invoiceRows.count();
        expect(rowCount).toBeGreaterThan(0);

        // Check for PDF download link
        const pdfLink = page.locator('a:has-text("Download PDF")').first();
        if (await pdfLink.isVisible().catch(() => false)) {
          await expect(pdfLink).toHaveAttribute('href', /.*\.pdf.*/);
        }
      }
    } else {
      // No subscription - verify empty state
      await expect(page.locator('text=No Active Subscription')).toBeVisible();
      await expect(page.locator('a:has-text("Choose a Plan")')).toBeVisible();
    }
  });

  test('should open billing directly from AccountDropdown', async ({ page }) => {
    // MOCK: Navigate directly to dashboard (assuming logged in)
    await page.goto('http://localhost:9000/en/dashboard');

    // Wait for dashboard to load
    await expect(page.locator('text=Welcome back')).toBeVisible({ timeout: 10000 });

    // Click on user avatar
    const avatarButton = page.locator('button:has(div[class*="rounded-full"])').first();
    await avatarButton.click();

    // Click "Billing" directly
    await page.click('text=Billing');

    // Verify AccountSettingsModal opened to Billing tab
    await expect(page.locator('text=Account Settings')).toBeVisible();
    await expect(page.locator('text=Billing & Subscription')).toBeVisible();

    // Verify we're on the billing tab (not profile)
    const billingTabButton = page.locator('button:has-text("Billing")');
    await expect(billingTabButton).toHaveClass(/bg-white.*border-brand-green/);
  });

  test('should navigate to billing tab in dashboard', async ({ page }) => {
    // Navigate to dashboard with billing tab
    await page.goto('http://localhost:9000/en/dashboard?tab=billing');

    // Wait for dashboard to load
    await expect(page.locator('text=Welcome back')).toBeVisible({ timeout: 10000 });

    // Verify billing tab is active
    const billingTab = page.locator('button:has-text("Billing & Plan")');
    await expect(billingTab).toHaveClass(/bg-brand-green/);

    // Verify BillingPanel is displayed
    const hasSubscription = await page.locator('text=Active Account, text=No Active Subscription').isVisible().catch(() => false);
    expect(hasSubscription).toBeTruthy();
  });

  test('should handle invoice download', async ({ page }) => {
    // Navigate to dashboard
    await page.goto('http://localhost:9000/en/dashboard');

    // Open billing via dropdown
    await page.locator('button:has(div[class*="rounded-full"])').first().click();
    await page.click('text=Billing');

    // Wait for invoices to load
    await page.waitForTimeout(2000);

    // Check if PDF download link exists
    const pdfLink = page.locator('a:has-text("Download PDF")').first();
    const hasPdfLink = await pdfLink.isVisible().catch(() => false);

    if (hasPdfLink) {
      // Verify link has proper attributes
      await expect(pdfLink).toHaveAttribute('target', '_blank');
      await expect(pdfLink).toHaveAttribute('rel', 'noopener noreferrer');

      // Verify href contains Stripe PDF URL
      const href = await pdfLink.getAttribute('href');
      expect(href).toContain('stripe.com');
    }
  });
});

test.describe('Billing Tab - Plan Display', () => {
  test('should display current plan correctly', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard');

    // Open billing
    await page.locator('button:has(div[class*="rounded-full"])').first().click();
    await page.click('text=Billing');

    // Wait for content to load
    await page.waitForTimeout(1000);

    const hasSubscription = await page.locator('text=Active Account').isVisible().catch(() => false);

    if (hasSubscription) {
      // Verify plan details are shown
      await expect(page.locator('text=Status')).toBeVisible();
      await expect(page.locator('text=Monthly Price')).toBeVisible();
      await expect(page.locator('text=Next Renewal')).toBeVisible();
      await expect(page.locator('text=Days Remaining')).toBeVisible();

      // Verify values are populated (not empty)
      const statusValue = page.locator('text=Active, text=Trialing').first();
      await expect(statusValue).toBeVisible();
    }
  });

  test('should show upgrade modal when clicking upgrade button', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard');

    // Open billing
    await page.locator('button:has(div[class*="rounded-full"])').first().click();
    await page.click('text=Billing');

    // Wait for content
    await page.waitForTimeout(1000);

    // Check if upgrade button exists
    const upgradeButton = page.locator('button:has-text("Upgrade Plan")');
    const hasButton = await upgradeButton.isVisible().catch(() => false);

    if (hasButton) {
      // Click upgrade button
      await upgradeButton.click();

      // Verify modal opens
      await expect(page.locator('text=Upgrade Your Plan, text=Change Plan')).toBeVisible({ timeout: 5000 });

      // Verify modal shows plan options
      const planCards = page.locator('div:has-text("tier"), div:has-text("Plan")');
      expect(await planCards.count()).toBeGreaterThan(0);
    }
  });
});
