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

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.py: {e}")
    sys.exit(1)

def test_user_management():
    driver = None
    try:
        driver = login_to_cms()
        print("Logged in, proceeding to User Management test")

        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "li.ant-menu-item"))
        )

        user_management_link = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "li.ant-menu-item a[href='/user-management']"))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", user_management_link)
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable(user_management_link))
        user_management_link.click()
        print("Clicked User Management link")

        user_management_title = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//h1[contains(text(), 'User Management')]"))
        ).text
        assert "User Management" in user_management_title
        time.sleep(1)

        add_user_button = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'ant-btn') and .//span[contains(text(), 'Add User')]]"))
        )
        add_user_button.click()
        print("Clicked Add User button")
        time.sleep(1)

        WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//h1[contains(text(), 'Add User')]"))
        )

        username_field = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.NAME, "username"))
        )
        username_field.clear()
        driver.execute_script("arguments[0].focus();", username_field)
        username_field.send_keys("m.marjorie")
        driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", username_field)
        driver.execute_script("arguments[0].dispatchEvent(new Event('blur'));", username_field)
        time.sleep(1)

        first_name_field = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.NAME, "firstname"))
        )
        first_name_field.clear()
        driver.execute_script("arguments[0].focus();", first_name_field)
        first_name_field.send_keys("Marjorie")
        driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", first_name_field)
        driver.execute_script("arguments[0].dispatchEvent(new Event('blur'));", first_name_field)
        time.sleep(1)

        last_name_field = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.NAME, "lastname"))
        )
        last_name_field.clear()
        driver.execute_script("arguments[0].focus();", last_name_field)
        last_name_field.send_keys("Magluyan")
        driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", last_name_field)
        driver.execute_script("arguments[0].dispatchEvent(new Event('blur'));", last_name_field)
        time.sleep(1)

        email_field = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.NAME, "email"))
        )
        email_field.clear()
        driver.execute_script("arguments[0].focus();", email_field)
        email_field.send_keys("example@gmail.com")
        driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", email_field)
        driver.execute_script("arguments[0].dispatchEvent(new Event('blur'));", email_field)
        time.sleep(1)

        WebDriverWait(driver, 15).until(EC.invisibility_of_element_located((By.CLASS_NAME, "ant-spin")))

        inactive_radio_label = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//label[contains(@class, 'ant-radio-wrapper') and normalize-space(.)='Inactive']"))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", inactive_radio_label)
        inactive_radio_label.click()
        time.sleep(1)

        marketing_personnel_label = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//label[contains(@class, 'ant-radio-wrapper') and normalize-space(.)='Marketing Personnel']"))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", marketing_personnel_label)
        marketing_personnel_label.click()
        time.sleep(1)

        generate_button = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Generate']"))
        )
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", generate_button)
        ActionChains(driver).move_to_element(generate_button).click().perform()
        time.sleep(1)

        password_field = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, "//button[normalize-space()='Generate']/following-sibling::input[1] | //input[contains(@class, 'ant-input')]"))
        )
        password_value = password_field.get_attribute("value")
        print("Default password generated:", password_value)

        submit_button = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Submit'] and contains(@style, 'background: rgb(231, 70, 16)')]"))
        )
        submit_button.click()
        print("Submitted Add User form")
        time.sleep(2)

        # ✅ Check if alert modal appears
        try:
            WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.CLASS_NAME, "ant-notification-notice"))
            )
            print("⚠️ Notification alert appeared")

            # 1. Click the X icon to close notification
            close_icon = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "i.ant-notification-close-icon"))
            )
            close_icon.click()
            print("Closed alert notification")

            # 2. Click Cancel
            cancel_button = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[span[text()='Cancel']]"))
            )
            cancel_button.click()
            print("Clicked Cancel on modal")

            # 3. Confirm Cancel by clicking Yes
            yes_button = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'ant-btn-primary') and .//span[text()='Yes']]"))
            )
            yes_button.click()
            print("Confirmed Cancel by clicking Yes")

        except Exception:
            print("No alert notification appeared; continuing test flow...")

       # Step 1: Search for "graxia"
        search_input = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "input[placeholder='Search']"))
        )
        search_input.clear()
        search_input.send_keys("graxia")
        print("Searched for username: graxia")

        # Wait for the result to show up
        time.sleep(3)  # Adjust if necessary depending on API delay

        # Step 2: Click the View icon next to the search result
        try:
            view_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//i[contains(@class, 'anticon-right-circle-o')]"))
            )
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", view_button)
            view_button.click()
            print("Clicked View icon for graxia")
        except Exception as e:
            print(f"❌ Failed to click View icon: {e}")
            driver.save_screenshot("view_click_failed.png")
            raise


        # Wait and click the Update button
        time.sleep(3)
        update_button = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Update']]"))
        )
        update_button.click()
        print("Clicked Update button")

        # Step 3: Change First Name after clicking View
        # Wait for the First Name input field to appear
        first_name_field = WebDriverWait(driver, 15).until(
            EC.visibility_of_element_located((By.NAME, "firstname"))
        )

        # Use JavaScript to clear the field properly
        driver.execute_script("arguments[0].value = '';", first_name_field)  # Clear the field using JS

        # Enter the new First Name
        first_name_field.send_keys("Graxi")  # Enter the new name
        print("Updated First Name to: Graxi")

        # After updating the first name, click the Submit button
        submit_button = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Submit']"))
        )
        submit_button.click()
        print("Clicked Submit button to save changes")

        # Step 1: Search for the graxia username again
        search_input = WebDriverWait(driver, 15).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "input.ant-input[placeholder='Search']"))
        )
        search_input.clear()  # Clear any existing value
        search_input.send_keys("graxia")  # Enter the username "graxia"
        print("Searched for username: graxia")

        # Step 2: Wait for and click the View button (same as before)
        view_button = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "i.anticon.anticon-right-circle-o"))
        )
        view_button.click()
        print("Clicked View button for graxia")

        # Step 3: Wait for the Active button to be clickable
        active_button = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "a.ant-dropdown-link.ant-dropdown-trigger"))
        )
        active_button.click()  # Click the Active dropdown
        print("Clicked Active dropdown")

        # Step 4: Wait for and select the Inactive option
        inactive_option = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.XPATH, "//li[contains(@class, 'ant-dropdown-menu-item') and normalize-space(text())='Inactive']"))
        )
        inactive_option.click()  # Click the Inactive option
        print("Selected Inactive from the dropdown")

        time.sleep(1)

        print("Waiting for 10 seconds before closing the browser...")
        time.sleep(10)  # Wait for 10 seconds

        # Close the browser
        driver.quit()
        print("Browser closed successfully.")
            

        return driver

    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("\nUser interrupted the script. Closing the browser.")
        if driver is not None:
            driver.quit()

if __name__ == "__main__":
    test_user_management()
