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

test.describe('Field Data Collection E2E', () => {
  test.beforeEach(async ({ page }) => {
    // Mock geolocation
    await page.context().grantPermissions(['geolocation']);
    await page.context().setGeolocation({ latitude: 14.6349, longitude: -90.5069 });
    
    // Navigate to the app
    await page.goto('/');
  });

  test('complete field data collection workflow', async ({ page }) => {
    // Login as field technician
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');

    // Wait for dashboard to load
    await expect(page.locator('[data-testid="dashboard"]')).toBeVisible();

    // Navigate to field application
    await page.click('[data-testid="field-app-link"]');
    await expect(page.locator('[data-testid="field-app"]')).toBeVisible();

    // Select project and rodal
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.waitForTimeout(1000); // Wait for rodales to load
    await page.selectOption('[data-testid="rodal-select"]', '1');

    // Start tree registration
    await page.click('[data-testid="start-registration-button"]');
    await expect(page.locator('[data-testid="tree-form"]')).toBeVisible();

    // Fill tree data form
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.selectOption('[data-testid="species-select"]', 'Pinus maximinoi');
    await page.fill('[data-testid="dap-input"]', '25.5');
    await page.fill('[data-testid="height-input"]', '15.2');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');

    // Verify GPS coordinates are captured
    await expect(page.locator('[data-testid="gps-coordinates"]')).toContainText('14.6349');
    await expect(page.locator('[data-testid="gps-coordinates"]')).toContainText('-90.5069');

    // Save tree data
    await page.click('[data-testid="save-tree-button"]');

    // Verify success message
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');

    // Verify form is reset for next entry
    await expect(page.locator('[data-testid="parcel-number-input"]')).toHaveValue('2'); // Auto-incremented
    await expect(page.locator('[data-testid="dap-input"]')).toHaveValue('');
    await expect(page.locator('[data-testid="height-input"]')).toHaveValue('');

    // Add second tree
    await page.selectOption('[data-testid="species-select"]', 'Cupressus lusitanica');
    await page.fill('[data-testid="dap-input"]', '30.0');
    await page.fill('[data-testid="height-input"]', '18.5');
    await page.selectOption('[data-testid="condition-select"]', 'Bifurcado');
    await page.click('[data-testid="save-tree-button"]');

    // Verify second tree is saved
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');

    // Check offline storage counter
    await expect(page.locator('[data-testid="offline-counter"]')).toContainText('2 registros pendientes');
  });

  test('handles unusual values with confirmation dialog', async ({ page }) => {
    // Login and navigate to tree form
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');
    await page.click('[data-testid="field-app-link"]');
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Fill form with unusual DAP value
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.selectOption('[data-testid="species-select"]', 'Pinus maximinoi');
    await page.fill('[data-testid="dap-input"]', '220'); // Unusual value
    await page.fill('[data-testid="height-input"]', '25');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');

    // Submit form
    await page.click('[data-testid="save-tree-button"]');

    // Verify confirmation dialog appears
    await expect(page.locator('[data-testid="confirmation-dialog"]')).toBeVisible();
    await expect(page.locator('[data-testid="confirmation-message"]')).toContainText('DAP de 220 cm es muy grande');

    // Confirm the unusual value
    await page.click('[data-testid="confirm-button"]');

    // Verify tree is saved
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');
  });

  test('works offline and syncs when online', async ({ page }) => {
    // Login and collect data while online
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');
    await page.click('[data-testid="field-app-link"]');
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Go offline
    await page.context().setOffline(true);
    await expect(page.locator('[data-testid="offline-indicator"]')).toContainText('Sin conexión');

    // Fill and save tree data while offline
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.selectOption('[data-testid="species-select"]', 'Pinus maximinoi');
    await page.fill('[data-testid="dap-input"]', '25.5');
    await page.fill('[data-testid="height-input"]', '15.2');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');
    await page.click('[data-testid="save-tree-button"]');

    // Verify offline save
    await expect(page.locator('[data-testid="success-message"]')).toContainText('guardado localmente');
    await expect(page.locator('[data-testid="offline-counter"]')).toContainText('1 registro pendiente');

    // Go back online
    await page.context().setOffline(false);
    await expect(page.locator('[data-testid="online-indicator"]')).toContainText('Conectado');

    // Sync data
    await page.click('[data-testid="sync-button"]');
    await expect(page.locator('[data-testid="sync-progress"]')).toBeVisible();

    // Verify sync completion
    await expect(page.locator('[data-testid="sync-success"]')).toContainText('Sincronización completada');
    await expect(page.locator('[data-testid="offline-counter"]')).toContainText('0 registros pendientes');
  });

  test('validates field inputs correctly', async ({ page }) => {
    // Login and navigate to form
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');
    await page.click('[data-testid="field-app-link"]');
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Try to submit empty form
    await page.click('[data-testid="save-tree-button"]');

    // Verify validation errors
    await expect(page.locator('[data-testid="parcel-error"]')).toContainText('requerido');
    await expect(page.locator('[data-testid="species-error"]')).toContainText('requerida');
    await expect(page.locator('[data-testid="dap-error"]')).toContainText('requerido');
    await expect(page.locator('[data-testid="height-error"]')).toContainText('requerida');

    // Test invalid DAP value
    await page.fill('[data-testid="dap-input"]', '-5');
    await page.blur('[data-testid="dap-input"]');
    await expect(page.locator('[data-testid="dap-error"]')).toContainText('debe ser mayor a 0');

    // Test invalid height value
    await page.fill('[data-testid="height-input"]', '100');
    await page.blur('[data-testid="height-input"]');
    await expect(page.locator('[data-testid="height-error"]')).toContainText('muy grande');

    // Fill valid values
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.selectOption('[data-testid="species-select"]', 'Pinus maximinoi');
    await page.fill('[data-testid="dap-input"]', '25.5');
    await page.fill('[data-testid="height-input"]', '15.2');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');

    // Submit should work now
    await page.click('[data-testid="save-tree-button"]');
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');
  });

  test('handles GPS errors gracefully', async ({ page }) => {
    // Deny geolocation permission
    await page.context().grantPermissions([]);
    
    // Login and navigate to form
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');
    await page.click('[data-testid="field-app-link"]');
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Verify GPS error is shown
    await expect(page.locator('[data-testid="gps-error"]')).toContainText('GPS no disponible');
    await expect(page.locator('[data-testid="retry-gps-button"]')).toBeVisible();

    // Fill form without GPS
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.selectOption('[data-testid="species-select"]', 'Pinus maximinoi');
    await page.fill('[data-testid="dap-input"]', '25.5');
    await page.fill('[data-testid="height-input"]', '15.2');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');

    // Should show warning about missing GPS
    await page.click('[data-testid="save-tree-button"]');
    await expect(page.locator('[data-testid="gps-warning"]')).toContainText('sin coordenadas GPS');

    // Confirm save without GPS
    await page.click('[data-testid="confirm-no-gps-button"]');
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');
  });

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

    // Login
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');

    // Navigate to field app
    await page.click('[data-testid="field-app-link"]');

    // Verify mobile layout
    await expect(page.locator('[data-testid="mobile-header"]')).toBeVisible();
    await expect(page.locator('[data-testid="mobile-navigation"]')).toBeVisible();

    // Select project and rodal
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Verify form is mobile-optimized
    await expect(page.locator('[data-testid="tree-form"]')).toHaveCSS('width', '100%');
    
    // Test touch interactions
    await page.tap('[data-testid="species-select"]');
    await page.tap('[data-testid="species-option-pinus"]');

    // Fill form using mobile interactions
    await page.fill('[data-testid="parcel-number-input"]', '1');
    await page.fill('[data-testid="dap-input"]', '25.5');
    await page.fill('[data-testid="height-input"]', '15.2');
    await page.selectOption('[data-testid="condition-select"]', 'Sano');

    // Save tree
    await page.tap('[data-testid="save-tree-button"]');
    await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');
  });

  test('bulk data entry workflow', async ({ page }) => {
    // Login and setup
    await page.fill('[data-testid="email-input"]', 'tecnico@example.com');
    await page.fill('[data-testid="password-input"]', 'password123');
    await page.click('[data-testid="login-button"]');
    await page.click('[data-testid="field-app-link"]');
    await page.selectOption('[data-testid="project-select"]', '1');
    await page.selectOption('[data-testid="rodal-select"]', '1');
    await page.click('[data-testid="start-registration-button"]');

    // Enter multiple trees quickly
    const treeData = [
      { species: 'Pinus maximinoi', dap: '25.5', height: '15.2', condition: 'Sano' },
      { species: 'Cupressus lusitanica', dap: '30.0', height: '18.5', condition: 'Bifurcado' },
      { species: 'Pinus maximinoi', dap: '22.3', height: '12.8', condition: 'Sano' },
      { species: 'Cupressus lusitanica', dap: '28.7', height: '16.9', condition: 'Plagado' },
      { species: 'Pinus maximinoi', dap: '35.2', height: '20.1', condition: 'Sano' }
    ];

    for (let i = 0; i < treeData.length; i++) {
      const tree = treeData[i];
      
      // Verify parcel number auto-increments
      await expect(page.locator('[data-testid="parcel-number-input"]')).toHaveValue((i + 1).toString());
      
      // Fill tree data
      await page.selectOption('[data-testid="species-select"]', tree.species);
      await page.fill('[data-testid="dap-input"]', tree.dap);
      await page.fill('[data-testid="height-input"]', tree.height);
      await page.selectOption('[data-testid="condition-select"]', tree.condition);
      
      // Save tree
      await page.click('[data-testid="save-tree-button"]');
      await expect(page.locator('[data-testid="success-message"]')).toContainText('Árbol guardado');
      
      // Wait for form reset
      await page.waitForTimeout(500);
    }

    // Verify all trees are stored offline
    await expect(page.locator('[data-testid="offline-counter"]')).toContainText('5 registros pendientes');

    // View summary
    await page.click('[data-testid="view-summary-button"]');
    await expect(page.locator('[data-testid="tree-count"]')).toContainText('5 árboles');
    await expect(page.locator('[data-testid="species-count"]')).toContainText('2 especies');
  });
});