import { test, expect } from '@playwright/test';

/**
 * Charts Test Suite for SAWIS Business Intelligence Dashboard
 * Tests the chart functionality, data visualization, and export features
 */
test.describe('SAWIS Charts and Data Visualization', () => {
  
  test.beforeEach(async ({ page }) => {
    // Navigate to the homepage before each test
    await page.goto('/');
    await page.waitForLoadState('networkidle');
    // Wait for initial data and charts to load
    await page.waitForTimeout(5000);
  });

  test('should display all chart sections on Overview tab', async ({ page }) => {
    // Verify all chart headings are present
    await expect(page.getByText('Export market per product type')).toBeVisible();
    await expect(page.getByText('Exports (L)')).toBeVisible();
    await expect(page.getByText('Cultivar / Type Exported')).toBeVisible();
    await expect(page.getByText('Export market volume by product type')).toBeVisible();
    await expect(page.getByText('Top Export Countries')).toBeVisible();
  });

  test('should display reporting period information', async ({ page }) => {
    // Check that reporting period is displayed for each chart
    const chartHeadings = page.locator('h4');
    await expect(chartHeadings.first()).toContainText('Reporting Period:');
    
    // Verify the reporting period format
    await expect(page.getByText(/Reporting Period: [A-Z]{3} \d{4} - [A-Z]{3} \d{4}/)).toBeVisible();
  });

  test('should have functional Tables buttons', async ({ page }) => {
    // Check for Tables buttons on chart sections
    const tablesButtons = page.getByRole('button', { name: 'Tables' });
    await expect(tablesButtons).toHaveCount(5); // Should have 5 Tables buttons
    
    // Click on first Tables button
    await tablesButtons.first().click();
    
    // Verify table view is displayed (or modal opens)
    // This may vary based on implementation
    await page.waitForTimeout(1000);
  });

  test('should have functional Export buttons', async ({ page }) => {
    // Check for Export buttons on chart sections
    const exportButtons = page.getByRole('button', { name: 'Export' });
    await expect(exportButtons).toHaveCount(5); // Should have 5 Export buttons
    
    // Click on first Export button
    await exportButtons.first().click();
    
    // Verify export functionality (may trigger download or show options)
    await page.waitForTimeout(1000);
  });

  test('should display chart data correctly', async ({ page }) => {
    // Wait for charts to fully load
    await page.waitForTimeout(3000);
    
    // Check that chart containers are present
    const chartContainers = page.locator('canvas, svg, [role="img"]');
    await expect(chartContainers).toHaveCount.greaterThan(0);
    
    // Verify that data is displayed (not just loading states)
    await expect(page.getByText(/[0-9,]+/)).toBeVisible(); // Should show numeric data
  });

  test('should handle chart interactions', async ({ page }) => {
    // Wait for charts to load
    await page.waitForTimeout(3000);
    
    // Try to interact with chart elements
    const chartElements = page.locator('canvas, svg, [role="img"]');
    
    if (await chartElements.count() > 0) {
      // Click on first chart element
      await chartElements.first().click();
      
      // Verify interaction doesn't break the page
      await expect(page.getByText('Export market per product type')).toBeVisible();
    }
  });

  test('should display loading states for charts', async ({ page }) => {
    // Reload page to see loading states
    await page.reload();
    
    // Check for loading indicators
    const loadingIndicators = page.locator('text="rotating-lines-loading"');
    await expect(loadingIndicators).toHaveCount.greaterThan(0);
    
    // Wait for charts to load
    await page.waitForTimeout(5000);
    
    // Verify loading states are replaced with content
    await expect(page.getByText('Export market per product type')).toBeVisible();
  });

  test('should handle chart data updates when filters change', async ({ page }) => {
    // Get initial chart data
    const initialData = await page.getByText(/[0-9,]+/).first().textContent();
    
    // Change a filter
    await page.getByText('Year').locator('..').getByText('2025').click();
    await page.getByText('2024').click();
    
    // Apply filter
    await page.getByRole('button', { name: 'Apply' }).click();
    
    // Wait for data to update
    await page.waitForTimeout(3000);
    
    // Get updated chart data
    const updatedData = await page.getByText(/[0-9,]+/).first().textContent();
    
    // Verify data has changed (this may vary based on actual data)
    expect(updatedData).toBeDefined();
  });

  test('should display chart legends and labels', async ({ page }) => {
    // Wait for charts to load
    await page.waitForTimeout(3000);
    
    // Check for chart legends and labels
    // Look for common chart elements
    const chartLabels = page.locator('text=/Packaged|Bulk|White|Red|Sparkling/');
    await expect(chartLabels).toHaveCount.greaterThan(0);
  });

  test('should handle chart responsiveness', async ({ page }) => {
    // Test mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });
    await page.waitForTimeout(2000);
    
    // Verify charts are still visible and functional
    await expect(page.getByText('Export market per product type')).toBeVisible();
    
    // Test tablet viewport
    await page.setViewportSize({ width: 768, height: 1024 });
    await page.waitForTimeout(2000);
    
    // Verify charts adapt to different screen sizes
    await expect(page.getByText('Export market per product type')).toBeVisible();
  });

  test('should have proper chart accessibility', async ({ page }) => {
    // Check for proper ARIA labels and roles on charts
    const chartElements = page.locator('[role="img"], canvas, svg');
    
    if (await chartElements.count() > 0) {
      // Verify chart elements are present
      await expect(chartElements.first()).toBeVisible();
    }
    
    // Check for proper heading structure
    await expect(page.locator('h4')).toHaveCount(5);
  });

  test('should handle chart export functionality', async ({ page }) => {
    // Set up download listener
    const downloadPromise = page.waitForEvent('download');
    
    // Click on Export button
    await page.getByRole('button', { name: 'Export' }).first().click();
    
    // Wait for download to start (if implemented)
    try {
      await downloadPromise;
      // Download started successfully
    } catch (error) {
      // Download may not be implemented or may show options instead
      // This is acceptable behavior
    }
  });

  test('should display chart tooltips on hover', async ({ page }) => {
    // Wait for charts to load
    await page.waitForTimeout(3000);
    
    // Try to hover over chart elements
    const chartElements = page.locator('canvas, svg, [role="img"]');
    
    if (await chartElements.count() > 0) {
      // Hover over first chart element
      await chartElements.first().hover();
      
      // Wait for potential tooltip
      await page.waitForTimeout(1000);
      
      // Verify page is still functional
      await expect(page.getByText('Export market per product type')).toBeVisible();
    }
  });

  test('should handle chart data filtering', async ({ page }) => {
    // Apply specific filters to test chart data filtering
    await page.getByText('Product Type').locator('..').getByText('7 options').click();
    await page.getByText('White').click();
    
    await page.getByText('Package Type').locator('..').getByText('2 options').click();
    await page.getByText('Packaged').click();
    
    // Apply filters
    await page.getByRole('button', { name: 'Apply' }).click();
    
    // Wait for charts to update
    await page.waitForTimeout(3000);
    
    // Verify charts reflect the filtered data
    await expect(page.getByText('Export market per product type')).toBeVisible();
  });

  test('should display chart data in different tabs', async ({ page }) => {
    // Test Overview tab (default)
    await expect(page.getByText('Export market per product type')).toBeVisible();
    
    // Navigate to Volume tab
    await page.getByRole('button', { name: 'Volume' }).click();
    await page.waitForTimeout(3000);
    
    // Verify Volume-specific charts
    await expect(page.getByText('Total Export (l)')).toBeVisible();
    
    // Navigate to Value tab
    await page.getByRole('button', { name: 'Value' }).click();
    await page.waitForTimeout(3000);
    
    // Verify Value-specific charts
    await expect(page.getByText('Total Export (l)')).toBeVisible();
    
    // Navigate to Price Range tab
    await page.getByRole('button', { name: 'Price Range' }).click();
    await page.waitForTimeout(3000);
    
    // Verify Price Range-specific charts
    await expect(page.getByText('Total Export (l)')).toBeVisible();
  });

  test('should handle chart performance with large datasets', async ({ page }) => {
    // Select all countries to test with large dataset
    await page.getByText('Country').locator('..').getByText('194 options').click();
    await page.getByRole('button', { name: 'Select All' }).click();
    
    // Apply filters
    await page.getByRole('button', { name: 'Apply' }).click();
    
    // Wait for charts to load with large dataset
    await page.waitForTimeout(5000);
    
    // Verify charts still load and are functional
    await expect(page.getByText('Export market per product type')).toBeVisible();
  });

  test('should display chart error states gracefully', async ({ page }) => {
    // This test would typically involve simulating network errors
    // For now, we'll verify the page handles missing data gracefully
    
    // Check for "No results found" message when applicable
    const noResultsMessage = page.getByText('No results found');
    
    if (await noResultsMessage.isVisible()) {
      // Verify error state is handled properly
      await expect(noResultsMessage).toBeVisible();
    }
  });

  test('should have consistent chart styling', async ({ page }) => {
    // Wait for charts to load
    await page.waitForTimeout(3000);
    
    // Check for consistent visual elements
    const chartHeadings = page.locator('h4');
    await expect(chartHeadings).toHaveCount(5);
    
    // Verify all charts have similar structure
    for (let i = 0; i < 5; i++) {
      await expect(chartHeadings.nth(i)).toContainText('Reporting Period:');
    }
  });
}); 