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

// Setup: Create screenshots directory if it doesn't exist
const screenshotDir = 'screenshots';
fs.mkdirSync(screenshotDir, { recursive: true });

// Wall coordinates (shared between tests)
const wallCoordinates = [
  { x: 147, y: 212 },
  { x: 138, y: 542 },
  { x: 619, y: 548 },
  { x: 614, y: 286 },
  { x: 693, y: 284 },
  { x: 696, y: 374 },
  { x: 820, y: 369 },
  { x: 823, y: 285 },
  { x: 889, y: 285 },
  { x: 899, y: 662 },
  { x: 1249, y: 661 },
  { x: 1238, y: 122 },
  { x: 142, y: 116 },
  { x: 53, y: 124 },
  { x: 147, y: 212 },
];

/**
 * Reusable function for creating or deleting walls.
 * @param {Object} page - Playwright page object
 * @param {Array} coordinates - Array of {x, y} objects representing wall points
 * @param {String} action - 'create' or 'delete'
 */
async function drawOrDeleteWalls(page, coordinates, action) {
  console.log(`${action === 'create' ? 'Creating' : 'Deleting'} walls...`);

  for (const { x, y } of coordinates) {
    console.log(`${action === 'create' ? 'Creating' : 'Deleting'} at (${x}, ${y})`);
    await simulatePointerClick(page, x, y);

    // Add a small delay between clicks to ensure proper interaction
    await page.waitForTimeout(300); // Adjust timeout if necessary
  }

  if (action === 'create') {
    // Finalize wall creation with right-click
    await simulatePointerClick(page, 100, 160, 'right'); // Right-click to finalize
  }
}

/**
 * Simulates a pointer click at specific coordinates.
 */
async function simulatePointerClick(page, x, y, button = 'left') {
  // Move to the desired position
  await page.mouse.move(x, y);

  // Simulate mouse down and up to mimic a real click
  await page.mouse.down({ button });
  await page.mouse.up({ button });
}

// Test 1: Create walls after moving canvas
test('Create walls after moving canvas', async ({ page }) => {
  // Increase the timeout for this test (default is fine)
  test.setTimeout(60000); // Set timeout to 60 seconds

  // Setup
  const screenshotDir = 'screenshots';
  fs.mkdirSync(screenshotDir, { recursive: true });

  // 1. Navigate to the application
  await page.goto('http://185.100.212.76:8200');
  await page.getByPlaceholder('Email').fill('ramkumar@tester.local');
  await page.getByPlaceholder('Password').fill('123456');
  await page.getByRole('button', { name: 'Continue', exact: true }).click();

  // 2. Switch to full-screen mode
  console.log('Switching to full-screen mode...');
  await page.keyboard.press('F11'); // Simulate pressing F11 to enter full-screen mode

  // 3. Switch to 2D mode
  await page.locator('.toggle-option:has-text("2d")').click();

  // 4. Move the canvas to the top position
  console.log('Moving canvas to the top position...');
  const canvas = page.locator('canvas').first();
  const canvasBox = await canvas.boundingBox();

  if (!canvasBox) {
    throw new Error('Canvas bounding box not found. Ensure the canvas is visible.');
  }

  // Start position (center of canvas)
  const startX = canvasBox.x + canvasBox.width / 2;
  const startY = canvasBox.y + canvasBox.height / 2;

  // Simulate a drag action to move the canvas
  await page.mouse.move(startX, startY);
  await page.mouse.down();

  // Move the mouse down while dragging
  await page.mouse.move(startX, startY + 100, {
    steps: 20, // Smooth movement
  });

  // Simultaneously scroll the page (if needed)
  await page.mouse.wheel(0, 500); // Scroll down 500px

  await page.mouse.up();

  // 5. Select the wall tool
  console.log('Selecting Wall tool...');
  await page.getByTitle('Wall').getByRole('img').click();

  await page.waitForTimeout(2000); // Wait for the wall tool to be active

  // 6. Draw walls using reusable function
  await drawOrDeleteWalls(page, wallCoordinates, 'create');

  // 7. Take a final screenshot after drawing walls
  const afterCreationPath = `${screenshotDir}/walls-created-after-moving-canvas.png`;
  await page.screenshot({ path: afterCreationPath });
  console.log(`Walls created. Screenshot saved at: ${afterCreationPath}`);
});

// Test 2: Delete walls after moving canvas
test('Delete walls after moving canvas', async ({ page }) => {
  // Increase the timeout specifically for this test
  test.setTimeout(120000); // Set timeout to 120 seconds (2 minutes)

  // Setup
  const screenshotDir = 'screenshots';
  fs.mkdirSync(screenshotDir, { recursive: true });

  // 1. Navigate to the application
  await page.goto('http://185.100.212.76:8200');
  await page.getByPlaceholder('Email').fill('ramkumar@tester.local');
  await page.getByPlaceholder('Password').fill('123456');
  await page.getByRole('button', { name: 'Continue', exact: true }).click();

  // 2. Switch to full-screen mode
  console.log('Switching to full-screen mode...');
  await page.keyboard.press('F11'); // Simulate pressing F11 to enter full-screen mode

  // 3. Switch to 2D mode
  await page.locator('.toggle-option:has-text("2d")').click();

  // 4. Move the canvas to the top position
  console.log('Moving canvas to the top position...');
  const canvas = page.locator('canvas').first();
  const canvasBox = await canvas.boundingBox();

  if (!canvasBox) {
    throw new Error('Canvas bounding box not found. Ensure the canvas is visible.');
  }

  // Start position (center of canvas)
  const startX = canvasBox.x + canvasBox.width / 2;
  const startY = canvasBox.y + canvasBox.height / 2;

  // Simulate a drag action to move the canvas
  await page.mouse.move(startX, startY);
  await page.mouse.down();

  // Move the mouse down while dragging
  await page.mouse.move(startX, startY + 100, {
    steps: 20, // Smooth movement
  });

  // Simultaneously scroll the page (if needed)
  await page.mouse.wheel(0, 500); // Scroll down 500px

  await page.mouse.up();

  // 5. Open the "3 dots" menu and select the delete tool
  console.log('Opening three-dot menu...');
  await page.locator('.drop-down-option-button > svg').click(); // Replace with the actual selector for the menu
  console.log('Selecting Delete option...');
  await page.locator('div').filter({ hasText: /^Delete$/ }).first().click(); // Replace with the actual selector for the delete option

  await page.waitForTimeout(2000); // Wait for the delete tool to be active

  // 6. Define specific points for deletion, including midpoints
  const deleteCoordinates = [
    { x: 147, y: 212 },
    { x: 138, y: 542 },
    { x: 146, y: 378 },
    { x: 619, y: 548 },
    { x: 341, y: 541 },
    { x: 614, y: 286 },
    { x: 146, y: 449 },
    { x: 693, y: 284 },
    { x: 619, y: 450 },
    { x: 138, y: 542 },
    { x: 696, y: 374 },
    { x: 758, y: 371.5 },
    { x: 820, y: 369 },
    { x: 823, y: 285 },
    { x: 889, y: 285 },
    { x: 899, y: 662 },
    { x: 1249, y: 661 },
    { x: 726, y: 374 },
    { x: 750, y: 121 },
    { x: 1238, y: 122 },
    { x: 142, y: 116 },
    { x: 142, y: 116 },
    { x: 53, y: 124 },
    { x: 142, y: 116 },
    { x: 147, y: 212 },
  ];

  // Add midpoints between consecutive points
  const enhancedDeleteCoordinates = [];
  for (let i = 0; i < deleteCoordinates.length - 1; i++) {
    const currentPoint = deleteCoordinates[i];
    const nextPoint = deleteCoordinates[i + 1];

    // Add the current point
    enhancedDeleteCoordinates.push(currentPoint);

    // Calculate and add the midpoint
    const midX = (currentPoint.x + nextPoint.x) / 2;
    const midY = (currentPoint.y + nextPoint.y) / 2;
    enhancedDeleteCoordinates.push({ x: midX, y: midY });
  }

  // Add the last point
  enhancedDeleteCoordinates.push(deleteCoordinates[deleteCoordinates.length - 1]);

  // Delete walls using reusable function
  await drawOrDeleteWalls(page, enhancedDeleteCoordinates, 'delete');

  // 7. Take a final screenshot after deleting walls
  const afterDeletionPath = `${screenshotDir}/walls-deleted-after-moving-canvas.png`;
  await page.screenshot({ path: afterDeletionPath });
  console.log(`Walls deleted. Screenshot saved at: ${afterDeletionPath}`);
});