import { test, expect, Page } from '@playwright/test';
import { createTestUser, cleanupTestUser, generateTestEmail } from '../helpers/test-helpers';

// Test data
const TEST_USER = {
  fullName: 'Test User',
  email: generateTestEmail(),
  password: 'TestPassword123!@#',
};

const COMPANY_INFO = {
  companyName: 'Test Medical Clinic',
  industry: 'healthcare',
  companySize: '11-50',
  country: 'UAE',
  city: 'dubai',
  phoneNumber: '+971 50 123 4567',
  website: 'www.testclinic.com',
};

const ONBOARDING_DATA = {
  goals: ['reduce-no-shows', 'automate-reminders'],
  hasCalendar: 'yes',
  calendarSystem: 'Google Calendar',
  hasWhatsApp: 'planning',
  teamSize: '4-10',
};

// Helper functions
async function navigateToPricing(page: Page, lang: string = 'en') {
  await page.goto(`http://localhost:9000/${lang}/pricing`);
  await expect(page).toHaveURL(new RegExp(`/${lang}/pricing`));
}

async function selectPricingPlan(page: Page, tierId: string = 'tier2') {
  // Wait for pricing cards to load
  await page.waitForSelector(`[data-tier-id="${tierId}"]`);

  // Click the Get Started button for the selected tier
  await page.click(`[data-tier-id="${tierId}"]`);

  // Should redirect to signup with package parameter
  await expect(page).toHaveURL(new RegExp(`/signup\\?plan=${tierId}`));
}

async function fillSignupForm(page: Page, userData: typeof TEST_USER) {
  // Fill in the signup form
  await page.fill('#fullName', userData.fullName);
  await page.fill('#email', userData.email);
  await page.fill('#password', userData.password);
  await page.fill('#confirmPassword', userData.password);

  // Submit the form
  await page.click('button[type="submit"]');
}

async function fillCompanyInfoForm(page: Page, companyData: typeof COMPANY_INFO) {
  // Fill company information
  await page.fill('#companyName', companyData.companyName);
  await page.selectOption('#industry', companyData.industry);
  await page.selectOption('#companySize', companyData.companySize);
  await page.selectOption('#country', companyData.country);

  // Wait for city dropdown to enable
  await page.waitForSelector('#city:not([disabled])');
  await page.selectOption('#city', companyData.city);

  // Optional fields
  await page.fill('#phoneNumber', companyData.phoneNumber);
  await page.fill('#website', companyData.website);

  // Submit the form
  await page.click('button[type="submit"]');
}

async function fillOnboardingForm(page: Page, onboardingData: typeof ONBOARDING_DATA) {
  // Select goals
  for (const goal of onboardingData.goals) {
    await page.click(`label:has(input[type="checkbox"]):has-text("${goal}")`);
  }

  // Integration preferences
  await page.check(`input[name="hasCalendar"][value="${onboardingData.hasCalendar}"]`);
  if (onboardingData.hasCalendar === 'yes') {
    await page.fill('input[placeholder*="Calendar"]', onboardingData.calendarSystem);
  }

  await page.check(`input[name="hasWhatsApp"][value="${onboardingData.hasWhatsApp}"]`);
  await page.selectOption('#teamSize', onboardingData.teamSize);

  // Submit the form
  await page.click('button[type="submit"]');
}

// Test suite
test.describe('Pricing-First Signup Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Navigate to a page first to establish context
    await page.goto('http://localhost:9000/en');

    // Then clear cookies and localStorage
    await page.context().clearCookies();
    await page.evaluate(() => localStorage.clear());
  });

  test.afterEach(async () => {
    // Cleanup test user if created
    await cleanupTestUser(TEST_USER.email);
  });

  test('Complete signup flow - Email/Password path', async ({ page }) => {
    // Step 1: Navigate to pricing page
    await navigateToPricing(page);

    // Verify pricing page elements
    await expect(page.locator('h1')).toContainText('Transparent & Flexible Pricing');
    await expect(page.locator('[data-tier-id="tier1"]')).toBeVisible();
    await expect(page.locator('[data-tier-id="tier2"]')).toBeVisible();
    await expect(page.locator('[data-tier-id="tier3"]')).toBeVisible();

    // Step 2: Select a pricing plan
    await selectPricingPlan(page, 'tier2');

    // Step 3: Fill signup form
    await expect(page.locator('h2')).toContainText('Create Account');
    await expect(page.locator('text=/Professional/')).toBeVisible(); // Package badge
    await fillSignupForm(page, TEST_USER);

    // Note: In a real test, you'd handle Stripe checkout or mock it
    // For now, we'll simulate successful payment and continue

    // Step 4: Email verification (skip in test - would be handled differently)
    // In production, this would involve OTP verification

    // Step 5: Company information
    await page.goto(`http://localhost:9000/en/signup/company-info`);
    await expect(page.locator('h1')).toContainText('Company Information');
    await fillCompanyInfoForm(page, COMPANY_INFO);

    // Step 6: Onboarding
    await expect(page).toHaveURL(/\/signup\/onboarding/);
    await expect(page.locator('h1')).toContainText('Tell Us About Your Goals');
    await fillOnboardingForm(page, ONBOARDING_DATA);

    // Step 7: Success page
    await expect(page).toHaveURL(/\/signup\/success/);
    await expect(page.locator('h1')).toContainText('Welcome');
  });

  test('Pricing page - Currency switching', async ({ page }) => {
    await navigateToPricing(page);

    // Select different currency
    await page.selectOption('select[value="GBP"]', 'USD');

    // Verify prices update (check for $ symbol)
    await expect(page.locator('[data-tier-id="tier2"] >> text=/$/')).toBeVisible();
  });

  test('Pricing page - Billing period toggle', async ({ page }) => {
    await navigateToPricing(page);

    // Click yearly billing
    await page.click('button:has-text("Yearly")');

    // Verify discount message appears
    await expect(page.locator('text=/Save 7%/')).toBeVisible();
    await expect(page.locator('text=/Billed annually/')).toBeVisible();
  });

  test('Company info form validation', async ({ page }) => {
    // Navigate directly to company info page (would normally require auth)
    await page.goto(`http://localhost:9000/en/signup/company-info`);

    // Try to submit empty form
    await page.click('button[type="submit"]');

    // Check for validation errors
    await expect(page.locator('text=/Company name is required/')).toBeVisible();
    await expect(page.locator('text=/Please select an industry/')).toBeVisible();
    await expect(page.locator('text=/Please select company size/')).toBeVisible();
  });

  test('Onboarding form - Goals selection', async ({ page }) => {
    // Navigate directly to onboarding page (would normally require auth)
    await page.goto(`http://localhost:9000/en/signup/onboarding`);

    // Try to submit without selecting goals
    await page.click('button[type="submit"]');

    // Check for validation error
    await expect(page.locator('text=/Please select at least one goal/')).toBeVisible();

    // Select goals and verify they're checked
    await page.click('label:has-text("Reduce No-Shows")');
    await expect(page.locator('input[type="checkbox"]:checked')).toHaveCount(1);
  });

  test('RTL support - Arabic language', async ({ page }) => {
    // Navigate to Arabic pricing page
    await navigateToPricing(page, 'ar');

    // Verify RTL layout
    await expect(page.locator('main[dir="rtl"]')).toBeVisible();

    // Verify Arabic text
    await expect(page.locator('h1')).toContainText('خطط تسعير شفافة ومرنة');

    // Select plan and navigate to signup
    await selectPricingPlan(page, 'tier2');

    // Verify Arabic signup page
    await expect(page.locator('[dir="rtl"]')).toBeVisible();
    await expect(page.locator('h2')).toContainText('إنشاء حساب');
  });

  test('Mobile responsive design', async ({ page }) => {
    // Set mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });

    await navigateToPricing(page);

    // Verify mobile layout - cards should stack vertically
    const cards = page.locator('[data-tier-id]');
    await expect(cards).toHaveCount(5);

    // Verify all cards are visible on mobile
    for (let i = 0; i < 5; i++) {
      await expect(cards.nth(i)).toBeVisible();
    }
  });

  test('Accessibility - Keyboard navigation', async ({ page }) => {
    await navigateToPricing(page);

    // Tab through interactive elements
    await page.keyboard.press('Tab'); // Skip to first interactive element

    // Tab to currency selector
    await page.keyboard.press('Tab');
    await expect(page.locator('select:focus')).toBeVisible();

    // Tab to billing toggle
    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');

    // Tab to first Get Started button
    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');

    // Press Enter to select plan
    await page.keyboard.press('Enter');
    await expect(page).toHaveURL(/\/signup/);
  });

  test('Skip options - Company info and onboarding', async ({ page }) => {
    // Navigate to company info
    await page.goto(`http://localhost:9000/en/signup/company-info`);

    // Click skip
    await page.click('button:has-text("Skip for now")');
    await expect(page).toHaveURL(/\/signup\/onboarding/);

    // Skip onboarding too
    await page.click('button:has-text("Skip for now")');

    // Should complete onboarding without goals
    await expect(page).toHaveURL(/\/signup\/success/);
  });
});

test.describe('Error Handling', () => {
  test('Invalid package parameter', async ({ page }) => {
    // Navigate to signup with invalid package
    await page.goto('http://localhost:9000/en/signup?plan=invalid_tier');

    // Should still show signup page but with default tier
    await expect(page.locator('h2')).toContainText('Create Account');
  });

  test('Network error handling', async ({ page }) => {
    // Block API requests
    await page.route('**/api/**', route => route.abort());

    await navigateToPricing(page);
    await selectPricingPlan(page);

    // Fill and submit signup form
    await fillSignupForm(page, TEST_USER);

    // Should show error message
    await expect(page.locator('text=/Failed to create account/')).toBeVisible();
  });

  test('Rate limiting', async ({ page }) => {
    // Make multiple rapid requests
    for (let i = 0; i < 6; i++) {
      await page.goto('http://localhost:9000/en/signup/company-info');
      await page.click('button[type="submit"]');
    }

    // Should show rate limit error
    await expect(page.locator('text=/Too many requests/')).toBeVisible();
  });
});

test.describe('Cross-browser Testing', () => {
  ['chromium', 'firefox', 'webkit'].forEach(browserName => {
    test(`Works in ${browserName}`, async ({ page }) => {
      await navigateToPricing(page);
      await expect(page.locator('h1')).toContainText('Transparent & Flexible Pricing');
      await selectPricingPlan(page);
      await expect(page).toHaveURL(/\/signup/);
    });
  });
});