import { remote } from 'webdriverio'


const driver = await remote({
  hostname: 'localhost',
  port: 4723,
  path: "/",
  capabilities: {
    platformName: "Android",
    "appium:automationName": "UiAutomator2",
    "appium:deviceName": "Android Emulator",
    "appium:app": "/Users/mohammedshafiuddin/WebDev/freshyo/apps/admin-ui/android/app/build/outputs/apk/debug/app-debug.apk" 
  }
})

// Conditional login - only if login screen is present
try {
  const loginInput = await driver.$('~login-name-input');
  await loginInput.waitForDisplayed({ timeout: 5000 });
  
  // Login screen exists - perform login
  console.log('Login screen found, performing login...');
  
  // Enter username
  await loginInput.click();
  await loginInput.setValue('admin1');
  
  // Enter password
  const passwordInput = await driver.$('~login-password-input');
  await passwordInput.click();
  await passwordInput.setValue('admin12345');
  
  // Click login button
  const loginButton = await driver.$('~login-button');
  await loginButton.click();
  
  // Wait for dashboard to load
  console.log('Waiting for dashboard...');
  await driver.$('~delivery-slots-menu-item').waitForDisplayed({ timeout: 10000 });
  console.log('Dashboard loaded!');
} catch (e) {
  // Login screen not found - already logged in or different screen
  console.log('Login screen not found, continuing...');
}

// Navigate to Delivery Slots
console.log('Navigating to Delivery Slots...');
const deliverySlotsMenu = await driver.$('~delivery-slots-menu-item');
await deliverySlotsMenu.waitForDisplayed({ timeout: 5000 });
await deliverySlotsMenu.click();

// Wait for slots page and click FAB
console.log('Waiting for slots page...');
const addSlotFab = await driver.$('~add-slot-fab');
await addSlotFab.waitForDisplayed({ timeout: 20000 });
await addSlotFab.click();

// Wait for slot form
console.log('Waiting for slot form...');
await driver.$('~delivery-time-picker').waitForDisplayed({ timeout: 5000 });

// Calculate target times
const now = new Date();
const targetDeliveryTime = new Date(now.getTime() + 2 * 60 * 60 * 1000); // 2 hours from now
const targetFreezeTime = new Date(now.getTime() + 1 * 60 * 60 * 1000 + 45 * 60 * 1000); // 1hr 45min from now

const deliveryHour = targetDeliveryTime.getHours();
const deliveryMinute = targetDeliveryTime.getMinutes();
const freezeHour = targetFreezeTime.getHours();
const freezeMinute = targetFreezeTime.getMinutes();

console.log(`Target delivery time: ${deliveryHour}:${deliveryMinute.toString().padStart(2, '0')}`);
console.log(`Target freeze time: ${freezeHour}:${freezeMinute.toString().padStart(2, '0')}`);

// Set delivery time
console.log('Setting delivery time...');
const deliveryTimePicker = await driver.$('~delivery-time-picker');
await deliveryTimePicker.click();

// Wait for time picker dialog
await driver.pause(1000);

try {
  // Find hour field and set it
  const hourField = await driver.$('android=new UiSelector().resourceId("android:id/hour")');
  await hourField.clearValue();
  await hourField.setValue(deliveryHour.toString());
  
  // Find minute field and set it
  const minuteField = await driver.$('android=new UiSelector().resourceId("android:id/minute")');
  await minuteField.clearValue();
  await minuteField.setValue(deliveryMinute.toString().padStart(2, '0'));
  
  // Click OK button
  const okButton = await driver.$('android=new UiSelector().resourceId("android:id/button1")');
  await okButton.click();
  console.log('Delivery time set successfully');
} catch (e) {
  console.log('Could not interact with time picker, using back button...');
  await driver.back();
}

// Set freeze time
console.log('Setting freeze time...');
const freezeTimePicker = await driver.$('~freeze-time-picker');
await freezeTimePicker.click();

// Wait for time picker dialog
await driver.pause(1000);

try {
  // Find hour field and set it
  const freezeHourField = await driver.$('android=new UiSelector().resourceId("android:id/hour")');
  await freezeHourField.clearValue();
  await freezeHourField.setValue(freezeHour.toString());
  
  // Find minute field and set it
  const freezeMinuteField = await driver.$('android=new UiSelector().resourceId("android:id/minute")');
  await freezeMinuteField.clearValue();
  await freezeMinuteField.setValue(freezeMinute.toString().padStart(2, '0'));
  
  // Click OK button
  const freezeOkButton = await driver.$('android=new UiSelector().resourceId("android:id/button1")');
  await freezeOkButton.click();
  console.log('Freeze time set successfully');
} catch (e) {
  console.log('Could not interact with time picker, using back button...');
  await driver.back();
}

// Select product group "All mutton items"
console.log('Selecting product group...');
const productGroupsDropdown = await driver.$('~product-groups-dropdown');
await productGroupsDropdown.click();

// Wait for dropdown and select "All mutton items"
await driver.pause(2000);

// Try to find and tap "All mutton items" option
try {
  const muttonOption = await driver.$('android=new UiSelector().textContains("All mutton items")');
  await muttonOption.waitForDisplayed({ timeout: 5000 });
  await muttonOption.click();
  console.log('Selected "All mutton items" group');
} catch (e) {
  console.log('Could not find "All mutton items" option, continuing...');
}

// Tap Done to close dropdown
const doneButton = await driver.$('~product-groups-dropdown-done');
if (await doneButton.isDisplayed()) {
  await doneButton.click();
}

// Create slot
console.log('Creating slot...');
const createSlotButton = await driver.$('~create-slot-button');
await createSlotButton.waitForDisplayed({ timeout: 5000 });
await createSlotButton.click();

// Wait for slot creation
console.log('Waiting for slot creation...');
await driver.pause(5000);

console.log('Slot creation test completed!');

// Keep the session open for verification or close it
// await driver.deleteSession();
