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
import os
import sys
import time

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_card_member(driver):
    screenshot_dir = os.path.join("screenshots", "card_member_test")
    os.makedirs(screenshot_dir, exist_ok=True)

    try:
        # Step 2: Expand Member Management dropdown
        member_management_link = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'ant-menu-submenu-title') and normalize-space()='Member Management']"))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", member_management_link)
        member_management_link.click()
        print("✅ Clicked Member Management to expand dropdown")

        # Step 3: Navigate directly to Card Member page
        driver.get("https://stag-cms.unioilapps.com/member-management/card-member")
        print("✅ Navigated directly to Card Member page")

        # Step 4: Wait for the search input and enter card number
        search_input = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, "//input[@type='text' and @placeholder='Search' and contains(@class, 'ant-input')]"))
        )
        search_input.clear()
        search_input.send_keys("1113168608851474")
        print("🔍 Entered card number in search bar")

        # Step 5: Wait for results to load
        time.sleep(3)  # Let results render

        # Step 6: Click the View icon
        view_icon = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//i[contains(@class, 'anticon-right-circle-o')]"))
        )
        view_icon.click()
        print("👁️ Clicked the View icon")

        # Step 7: Wait for 5 seconds to allow viewing the details
        time.sleep(5)
        print("⏳ Waited for 5 seconds after viewing card details")

        # Step 8: Go back to Card Member page
        card_member_link = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//a[@href='/member-management/card-member']"))
        )
        card_member_link.click()
        print("🔙 Clicked 'Card Member' link to go back")

        # Step 9: Wait for the page to reload
        time.sleep(3)

        # Step 10: Take a final screenshot after returning
        screenshot_path = os.path.join(screenshot_dir, "returned_to_card_member.png")
        driver.save_screenshot(screenshot_path)
        print(f"📸 Screenshot saved at: {screenshot_path}")

        print("✅ Card Member test completed.")
    except Exception as e:
        print(f"❌ Test failed: {e}")
        driver.save_screenshot(os.path.join(screenshot_dir, "error_card_member.png"))
        print("📸 Error screenshot saved.")
        raise

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


def test_locked_accounts(driver):
    screenshot_dir = os.path.join("screenshots", "locked_accounts_test")
    os.makedirs(screenshot_dir, exist_ok=True)

    try:
        # Step 1: Navigate directly to Locked Accounts
        locked_accounts_url = "https://stag-cms.unioilapps.com/member-management/lock-account"
        driver.get(locked_accounts_url)
        print(f"🔐 Navigated to Locked Accounts page: {locked_accounts_url}")

        # Step 2: Take screenshot of the Locked Accounts page
        screenshot_path = os.path.join(screenshot_dir, "locked_accounts_page.png")
        driver.save_screenshot(screenshot_path)
        print(f"📸 Screenshot saved at: {screenshot_path}")

        # Step 11: Search for another card number
        search_input = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, "//input[@type='text' and @placeholder='Search' and contains(@class, 'ant-input')]"))
        )
        search_input.clear()
        search_input.send_keys("1100768101171208")
        print("🔍 Entered card number in search bar")

        time.sleep(3)  # Let results render

        # Step 12: Click the View icon
        second_view_icon = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//i[contains(@class, 'anticon-right-circle-o')]"))
        )
        second_view_icon.click()
        print("👁️ Clicked View icon for the card")

        # Step 13: Wait for 3 seconds
        time.sleep(3)

        # Step 14: Click the Activate Account button
        activate_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[span[text()='Activate Account']]"))
        )
        activate_button.click()
        print("✅ Clicked 'Activate Account' button")


        print("✅ Locked Accounts test completed. Keeping browser open for 10 seconds...")
        time.sleep(10)

    except Exception as e:
        # Do not raise error, just print and continue
        print(f"⚠️ Test failed while accessing Locked Accounts: {e}")
        driver.save_screenshot(os.path.join(screenshot_dir, "error_locked_accounts.png"))
        print("📸 Error screenshot saved.")

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


def main():
    driver = None

    try:
        # Step 1: Get driver from login module
        try:
            driver = login_to_cms()
            print("✅ Driver obtained from login_to_cms")
        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")

        # First, run the Card Member test
        test_card_member(driver)

        # Then, run the Locked Accounts test
        test_locked_accounts(driver)

    except Exception as e:
        print(f"❌ Test failed: {e}")
        if driver:
            driver.quit()
        raise

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


if __name__ == "__main__":
    main()
