from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import sys
import os

# Debug: Print the current working directory and list files
print(f"Current working directory: {os.getcwd()}")
print(f"Files in directory: {os.listdir(os.getcwd())}")

try:
    from login import login_to_cms
    print("✅ Successfully imported login_to_cms from login.py")
except ImportError as e:
    print(f"❌ Failed to import login_to_cms: {e}")
    sys.exit(1)

def test_home_page_mobile():
    driver = None
    try:
        # Initialize the driver explicitly if test_member_management doesn't
        try:
            driver = login_to_cms()
            print("Driver obtained")
        except Exception as e:
            print(f"Failed to get driver from login to cms: {e}")
            driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
            print("Initialized new Chrome driver")
        
        print("Proceeding to Home Page (Mobile) test")

        # Debug: Log all sidebar menu items to find the correct label
        sidebar_items = WebDriverWait(driver, 20).until(
            EC.presence_of_all_elements_located((By.XPATH, "//div[contains(@class, 'ant-menu-submenu-title')]"))
        )
        print("Sidebar submenu items found:")
        for item in sidebar_items:
            item_text = item.text.strip()
            item_classes = driver.execute_script("return arguments[0].getAttribute('class');", item)
            print(f" - Text: '{item_text}', Classes: {item_classes}")

        # Navigate to Home dropdown and click to expand
        home_link = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'ant-menu-submenu-title') and contains(normalize-space(), 'Home')]"))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", home_link)
        
        max_attempts = 3
        for attempt in range(max_attempts):
            try:
                home_link.click()
                print("Clicked Home to expand dropdown")
                break
            except Exception as e:
                print(f"Attempt {attempt + 1}/{max_attempts} to click Home failed: {e}")
                time.sleep(1)
                if attempt == max_attempts - 1:
                    raise Exception("Failed to click Home dropdown after multiple attempts")

        # Navigate directly to Photo Slider page
        driver.get("https://stag-cms.unioilapps.com/home-page/")
        print("Navigated to Photo Slider page directly via URL")

        # Locate the search input field
        search_input = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//input[contains(@class, 'ant-input')]"))
        )
        time.sleep(1)
        print("Search input field is visible")

        search_input.clear()
        search_input.send_keys("S&R")
        search_input.send_keys(Keys.RETURN)
        print("Typed 'S&R' into the search field and pressed Enter")

        # Wait for the "S&R" row to appear
        loyalty_row = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//td[contains(text(), 'S&R')]"))
        )
        time.sleep(1)
        print("S&R row is visible")
        print(f"Found row text: {loyalty_row.text}")

        # Locate the checkbox input for the "S&R" row
        checkbox_input = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.XPATH, "//td[contains(text(), 'S&R')]/preceding-sibling::td//input[@type='checkbox']"))
        )

        # Scroll into view
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox_input)
        time.sleep(1)

        # Try checking via JS click on its <label> (if it exists)
        try:
            label = checkbox_input.find_element(By.XPATH, "./ancestor::label")
            driver.execute_script("arguments[0].click();", label)
            print("Clicked checkbox label using JS")
        except:
            # If no label, click the checkbox directly
            driver.execute_script("arguments[0].click();", checkbox_input)
            print("Clicked checkbox input using JS")

        # Confirm it’s checked
        time.sleep(1)
        checked = driver.execute_script("return arguments[0].checked;", checkbox_input)
        print(f"Checkbox is checked: {checked}")

        if not checked:
            raise Exception("Checkbox is not checked after click.")

        # Wait for table to update (with or without results)
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'ant-table')]"))
        )
        time.sleep(1)  # Small buffer for any animation

        # Test completes here, no more actions after this point.
        print("✅ Test completed successfully. Browser will remain open. Press Ctrl+C to close the browser.")
        while True:
            time.sleep(1)

    except Exception as e:
        print(f"❌ Test failed: {e}")
        if driver is not None:
            driver.save_screenshot("error.png")
            print("Screenshot saved as error.png for debugging")
        if driver is not None:
            driver.quit()
        raise

    except KeyboardInterrupt:
        print("\n👋 User interrupted the script. Closing the browser.")
        if driver is not None:
            driver.quit()

if __name__ == "__main__":
    test_home_page_mobile()
