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

// Forklift coordinates
const forkliftCoordinates = [
  { x: 206, y: 250 },
  { x: 206, y: 281 },
  { x: 200, y: 307 },
  { x: 257, y: 251 },
  { x: 260, y: 277 },
  { x: 255, y: 304 },
];

// AGV coordinates
const agvCoordinates = [
  { x: 309, y: 325 },
  { x: 454, y: 287 },
  { x: 608, y: 282 },
  { x: 305, y: 417 },
  { x: 455, y: 424 },
  { x: 640, y: 173 },
  { x: 875, y: 227 },
  { x: 1059, y: 349 },
  { x: 977, y: 490 },
  { x: 1155, y: 492 },
];

/**
 * Common setup function for logging in and switching to full-screen mode.
 */
async function loginAndSetup(page) {
  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();
  console.log('Switching to full-screen mode...');
  await page.keyboard.press('F11'); // Simulate pressing F11 to enter full-screen mode
}

/**
 * Common function to move the canvas.
 */
async function moveCanvas(page) {
  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.');
  }
  const startX = canvasBox.x + canvasBox.width / 2;
  const startY = canvasBox.y + canvasBox.height / 2;
  await page.mouse.move(startX, startY);
  await page.mouse.down();
  await page.mouse.move(startX, startY + 100, { steps: 20 });
  await page.mouse.wheel(0, 500); // Scroll down 500px
  await page.mouse.up();
}

/**
 * Function to place an asset on the canvas using simulated drag-and-drop.
 * @param {Object} page - Playwright page object
 * @param {String} assetSelector - Selector for the asset to select (e.g., '#forklift', '#agv')
 * @param {Array} coordinates - Array of {x, y} objects representing drop positions
 */
async function placeAssetOnCanvas(page, assetSelector, coordinates) {
  console.log(`Placing asset ${assetSelector} on canvas...`);

  // Step 1: Select the "Vehicles" category
  console.log('Waiting for #Vehicles to be visible...');
  await page.waitForSelector('#Vehicles', { state: 'visible' }); // Wait for the element to be visible
  await page.locator('#Vehicles').click();

  // Step 2: Locate the asset
  const asset = page.locator(assetSelector);

  // Step 3: Place the asset at the specified coordinates
  for (const { x, y } of coordinates) {
    console.log(`Placing asset at (${x}, ${y})`);
    const target = page.locator('canvas'); // Target the canvas

    // Get bounding boxes for the asset and canvas
    const assetBox = await asset.boundingBox();
    const canvasBox = await target.boundingBox();

    if (!assetBox || !canvasBox) {
      throw new Error('Asset or canvas bounding box not found.');
    }

    // Calculate relative positions
    const assetCenterX = assetBox.x + assetBox.width / 2;
    const assetCenterY = assetBox.y + assetBox.height / 2;

    // Simulate drag-and-drop manually
    await page.mouse.move(assetCenterX, assetCenterY); // Move to the asset
    await page.mouse.down(); // Press the left mouse button
    await page.mouse.move(canvasBox.x + x, canvasBox.y + y, { steps: 50 }); // Move to the target on the canvas
    await page.mouse.up(); // Release the left mouse button

    // Trigger custom drag-and-drop events
    await page.evaluate(
      ({ assetSelector, targetSelector, x, y }) => {
        const asset = document.querySelector(assetSelector);
        const target = document.querySelector(targetSelector);

        // Trigger drag-and-drop events
        const dragStartEvent = new Event('dragstart', { bubbles: true });
        asset.dispatchEvent(dragStartEvent);

        const dragOverEvent = new Event('dragover', { bubbles: true });
        target.dispatchEvent(dragOverEvent);

        const dropEvent = new Event('drop', { bubbles: true });
        target.dispatchEvent(dropEvent);
      },
      { assetSelector, targetSelector: 'canvas', x, y } // Wrap arguments in an object
    );

    // Add a small delay between placements
    await page.waitForTimeout(500);
  }
}

/**
 * Main test case for adding Forklift and AGV assets.
 */
test('Add Forklift and AGV assets to the canvas', async ({ page }) => {
  test.setTimeout(120000); // Set timeout to 2 minutes

  // Step 1: Login and setup
  await loginAndSetup(page);

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

  // Step 3: Move the canvas to the desired position
  await moveCanvas(page);

  // Step 4: Click the toggle sidebar button
  console.log('Toggling sidebar...');
  await page.locator(".toggle-sidebar-ui-button.active").click();
  await page.waitForTimeout(2000); // Wait for the sidebar to toggle

  // Step 5: Open the "Assets" tab
  console.log('Opening the Assets tab...');
  await page.getByText('Assets').click();

  // Step 6: Add Forklift assets
  console.log('Adding Forklift assets...');
  await placeAssetOnCanvas(page, '#forklift', forkliftCoordinates);

  // Step 7: Add AGV assets
  console.log('Adding AGV assets...');
  await placeAssetOnCanvas(page, '#agv', agvCoordinates);

  // Step 8: Take a final screenshot
  console.log('Taking a final screenshot...');
  await page.screenshot({ path: 'assets-added.png' });

  // Step 9: Add assertions to verify assets are placed
  console.log('Verifying assets are placed on the canvas...');
  const forkliftCount = await page.locator('.forklift-asset').count(); // Replace with the actual selector for forklifts
  const agvCount = await page.locator('.agv-asset').count(); // Replace with the actual selector for AGVs

  expect(forkliftCount).toBeGreaterThan(0, 'No forklift assets were placed on the canvas.');
  expect(agvCount).toBeGreaterThan(0, 'No AGV assets were placed on the canvas.');

  console.log('Assertions passed: Assets are successfully placed on the canvas.');
});