/**
 * E2E Tests: Subscription Upgrade Flow
 * Tests the complete user journey for upgrading subscription plans
 */

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

test.describe('Subscription Upgrade Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Set base URL
    await page.goto('http://localhost:9000/ar');
  });

  test('should display subscription details on dashboard', async ({ page }) => {
    // This test assumes user is already logged in
    // You may need to implement login flow first

    await page.goto('http://localhost:9000/ar/dashboard');

    // Wait for dashboard to load
    await page.waitForSelector('text=لوحة العيادة', { timeout: 10000 });

    // Click billing tab
    await page.click('button:has-text("الفوترة والخطة")');

    // Wait for subscription details to load
    await page.waitForSelector('text=خطتك الحالية', { timeout: 5000 });

    // Verify subscription card is displayed
    const subscriptionCard = page.locator('[class*="from-brand-green"]').first();
    await expect(subscriptionCard).toBeVisible();

    // Verify payment method section exists
    const paymentMethodSection = page.locator('text=طريقة الدفع');
    await expect(paymentMethodSection).toBeVisible();

    // Verify setup fee section exists
    const setupFeeSection = page.locator('text=رسوم الإعداد');
    await expect(setupFeeSection).toBeVisible();
  });

  test('should display billing history table', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Navigate to billing tab
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(1000);

    // Verify billing history section
    const billingHistoryHeading = page.locator('text=آخر المعاملات');
    await expect(billingHistoryHeading).toBeVisible();

    // Check for "View all" link
    const viewAllLink = page.locator('a:has-text("عرض الكل")');
    await expect(viewAllLink).toBeVisible();
  });

  test('should navigate to full billing history page', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Click billing tab
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(500);

    // Click "Full Billing History" link
    await page.click('a:has-text("سجل الفواتير الكامل")');

    // Verify navigation to billing page
    await expect(page).toHaveURL(/\/ar\/dashboard\/billing/);

    // Verify billing page loaded
    const pageTitle = page.locator('h1:has-text("الفواتير والاشتراك")');
    await expect(pageTitle).toBeVisible();

    // Verify subscription details component
    const subscriptionDetails = page.locator('text=خطتك الحالية');
    await expect(subscriptionDetails).toBeVisible();

    // Verify complete billing history
    const billingHistory = page.locator('text=سجل الفواتير');
    await expect(billingHistory).toBeVisible();
  });

  test('should show upgrade button and navigate to pricing', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Click billing tab
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(500);

    // Click upgrade button
    const upgradeButton = page.locator('a:has-text("ترقية الخطة")').first();
    await expect(upgradeButton).toBeVisible();

    // Click and verify navigation
    await upgradeButton.click();
    await expect(page).toHaveURL(/\/ar\/pricing/);
  });

  test('should display payment method details when available', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Navigate to billing
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(1000);

    // Check for payment method card
    const paymentMethodCard = page.locator('text=طريقة الدفع');
    await expect(paymentMethodCard).toBeVisible();

    // If payment method exists, verify card details are shown
    const cardBrandElement = page.locator('[class*="bg-slate-900"]').filter({ hasText: /VISA|MC|AMEX/i });
    const hasPaymentMethod = await cardBrandElement.count() > 0;

    if (hasPaymentMethod) {
      // Verify last 4 digits pattern
      const cardLastFour = page.locator('text=/•••• \\d{4}/');
      await expect(cardLastFour).toBeVisible();
    }
  });

  test('should display setup fee status correctly', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Navigate to billing
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(1000);

    // Check setup fee section
    const setupFeeSection = page.locator('text=رسوم الإعداد');
    await expect(setupFeeSection).toBeVisible();

    // Verify either "Paid" or "Not paid yet" status
    const paidStatus = page.locator('text=تم الدفع');
    const unpaidStatus = page.locator('text=لم يتم دفعها بعد');

    const hasPaidStatus = await paidStatus.count() > 0;
    const hasUnpaidStatus = await unpaidStatus.count() > 0;

    expect(hasPaidStatus || hasUnpaidStatus).toBe(true);
  });

  test('should show trial period information when applicable', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Navigate to billing
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(1000);

    // Look for trial period indicator
    const trialText = page.locator('text=/تنتهي الفترة التجريبية|التجديد التالي/');
    await expect(trialText).toBeVisible();
  });

  test('should display billing events with correct formatting', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard');

    // Navigate to billing history page
    await page.click('button:has-text("الفوترة والخطة")');
    await page.waitForTimeout(500);
    await page.click('a:has-text("سجل الفواتير الكامل")');

    // Wait for billing history table
    await page.waitForSelector('table', { timeout: 5000 });

    // Verify table headers
    const headers = ['التاريخ', 'الحدث', 'المبلغ', 'التفاصيل'];
    for (const header of headers) {
      await expect(page.locator(`th:has-text("${header}")`)).toBeVisible();
    }

    // Check if any rows exist
    const rows = page.locator('tbody tr');
    const rowCount = await rows.count();

    if (rowCount > 0) {
      // Verify first row has all expected cells
      const firstRow = rows.first();
      await expect(firstRow.locator('td').nth(0)).toBeVisible(); // Date
      await expect(firstRow.locator('td').nth(1)).toBeVisible(); // Event
      await expect(firstRow.locator('td').nth(2)).toBeVisible(); // Amount
      await expect(firstRow.locator('td').nth(3)).toBeVisible(); // Details
    }
  });
});

test.describe('Subscription Upgrade API Integration', () => {
  test('should successfully upgrade via API', async ({ request }) => {
    // Note: This requires authentication cookie
    // You'll need to implement login flow first to get valid session

    const response = await request.post('http://localhost:9000/api/subscription/upgrade', {
      data: {
        subscriptionId: 'sub_test_123',
        newTierId: 'tier3',
        billingPeriod: 'monthly',
        currency: 'qar',
      },
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // For unauthenticated requests, expect 401
    if (response.status() === 401) {
      const data = await response.json();
      expect(data.error).toBe('Unauthorized');
    }

    // For authenticated successful upgrade, expect 200
    if (response.status() === 200) {
      const data = await response.json();
      expect(data.success).toBe(true);
      expect(data.newTierId).toBe('tier3');
      expect(data.prorationAmount).toBeDefined();
    }
  });

  test('should reject invalid tier upgrades', async ({ request }) => {
    const response = await request.post('http://localhost:9000/api/subscription/upgrade', {
      data: {
        subscriptionId: 'sub_test_123',
        newTierId: 'invalid_tier',
        billingPeriod: 'monthly',
        currency: 'qar',
      },
    });

    // Should fail validation even if unauthenticated
    const data = await response.json();

    if (response.status() === 400) {
      expect(data.error).toBeTruthy();
    }
  });
});

test.describe('Billing History Display', () => {
  test('should format amounts correctly in QAR', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard/billing');

    // Wait for page load
    await page.waitForSelector('h1:has-text("الفواتير والاشتراك")', { timeout: 5000 });

    // Look for any QAR amount
    const amountPattern = page.locator('text=/\\d+\\.\\d{2} QAR/');
    const hasAmounts = await amountPattern.count() > 0;

    // If amounts exist, verify format is correct (XXX.XX QAR)
    if (hasAmounts) {
      const firstAmount = await amountPattern.first().textContent();
      expect(firstAmount).toMatch(/\d+\.\d{2} QAR/);
    }
  });

  test('should show setup fee as separate line item', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard/billing');
    await page.waitForTimeout(2000);

    // Look for setup fee event
    const setupFeeEvent = page.locator('text=رسوم الإعداد');
    const hasSetupFee = await setupFeeEvent.count() > 0;

    if (hasSetupFee) {
      // Verify setup fee icon
      const setupFeeIcon = page.locator('text=💰');
      await expect(setupFeeIcon).toBeVisible();
    }
  });

  test('should display card information in billing history', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dashboard/billing');
    await page.waitForTimeout(2000);

    // Look for card pattern (VISA •••• 4242)
    const cardPattern = page.locator('text=/VISA|MC|AMEX|MASTERCARD/i');
    const hasCardInfo = await cardPattern.count() > 0;

    if (hasCardInfo) {
      // Verify last 4 pattern
      const lastFourPattern = page.locator('text=/•••• \\d{4}/');
      await expect(lastFourPattern.first()).toBeVisible();
    }
  });
});
