from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import sys

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

def test_station_locator():
    driver = None
    try:
        driver = login_to_cms()
        wait = WebDriverWait(driver, 10)
        actions = ActionChains(driver)

        print("✅ Logged in")

        # Wait for the menu to load
        time.sleep(3)

        # Find the Station Locator menu item by its visible text
        station_locator = wait.until(
            EC.presence_of_element_located(
                (By.XPATH, '//span[normalize-space()="Station Locator"]/ancestor::div[contains(@class,"ant-menu-submenu-title")]')
            )
        )

        # Hover over the menu item to reveal submenu
        actions.move_to_element(station_locator).perform()
        time.sleep(1)

        # Click Station Locator (fallback to JS if necessary)
        try:
            station_locator.click()
            print("✅ Clicked Station Locator (regular click)")
        except:
            driver.execute_script("arguments[0].click();", station_locator)
            print("✅ Clicked Station Locator (JS fallback)")

        # Wait for Branches to appear
        branches_link = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//a[normalize-space()="Branches"]'))
        )
        branches_link.click()
        print("✅ Clicked on Branches")

        # 3. Click Add Branch
        add_branch_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Add branch"]]'))
        )
        add_branch_button.click()
        print("✅ Clicked on 'Add branch'")

        # 4. Enter branch code
        branch_code_input = wait.until(
            EC.presence_of_element_located((By.XPATH, '//input[@name="code"]'))
        )
        branch_code_input.send_keys("Marjorie Branch Code")
        print("✅ Entered branch code")

        # 5. Enter branch name
        branch_name_input = driver.find_element(By.XPATH, '//input[@name="name"]')
        branch_name_input.send_keys("Marjorie Branch Name")
        print("✅ Entered branch name")

        # 6. Enter details
        details_input = driver.find_element(By.XPATH, '//input[@name="details"]')
        details_input.send_keys("Marjorie Details")
        print("✅ Entered branch details")

        # 7. Click Save button
        save_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Save"]]'))
        )
        save_button.click()
        print("✅ Clicked on 'Save'")

      # 8. Handle error modal if branch already exists
        try:
            error_icon = WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.XPATH, '//i[@aria-label="icon: close" and contains(@class, "ant-notification-close-icon")]'))
            )
            driver.execute_script("arguments[0].click();", error_icon)
            print("✅ Closed the error notification")
        except:
            print("ℹ️ No error modal appeared")


        # 9. Click Cancel button
        cancel_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Cancel"]]'))
        )
        cancel_button.click()
        print("✅ Clicked on 'Cancel'")

        # 10. Click Yes on confirmation dialog
        confirmation_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Yes"]]'))
        )
        confirmation_button.click()
        print("✅ Clicked on 'Yes' in confirmation")


        # Re-open "Station Locator" submenu if collapsed (after navigating to Branches)
        station_locator = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located(
                (By.XPATH, '//span[normalize-space()="Station Locator"]/ancestor::div[contains(@class,"ant-menu-submenu-title")]')
            )
        )
        actions.move_to_element(station_locator).perform()
        time.sleep(1)

        try:
            station_locator.click()
            print("🔄 Re-clicked Station Locator (regular click)")
        except:
            driver.execute_script("arguments[0].click();", station_locator)
            print("🔄 Re-clicked Station Locator (JS fallback)")

        # Now click "Stations"
        stations_link = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//a[@href="/stations" and contains(text(), "Stations")]'))
        )
        stations_link.click()
        print("✅ Clicked on 'Stations'")


        # Click "Upload Prices"
        upload_prices_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Upload Prices"]]'))
        )
        upload_prices_btn.click()
        print("✅ Clicked 'Upload Prices'")

        # Click "Close" on the modal
        close_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Close"]]'))
        )
        close_button.click()
        print("✅ Closed the upload modal")

        # Click "Next Page"
        next_page = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//li[@title="Next Page" and @aria-disabled="false"]'))
        )
        next_page.click()
        print("➡️ Moved to next page")

        # Wait a bit for content to update
        time.sleep(2)

        # Click "Previous Page"
        prev_page = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//li[@title="Previous Page" and @aria-disabled="false"]'))
        )
        prev_page.click()
        print("⬅️ Moved back to previous page")


        # Wait and click the green plus-circle icon (add station)
        plus_icon = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//span[@role="img" and @aria-label="plus-circle"]'))
        )
        plus_icon.click()
        print("✅ Clicked the green plus-circle icon")

        # Wait and click Cancel button in the modal/form
        cancel_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Cancel"]]'))
        )
        cancel_button.click()
        print("✅ Clicked 'Cancel'")

        # Wait and click Yes on confirmation
        yes_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Yes"]]'))
        )
        yes_button.click()
        print("✅ Clicked 'Yes' on confirmation")


        # Re-open Station Locator dropdown (if collapsed)
        station_locator_menu = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[normalize-space()="Station Locator"]/ancestor::div[contains(@class,"ant-menu-submenu-title")]'))
        )
        driver.execute_script("arguments[0].scrollIntoView(true);", station_locator_menu)
        station_locator_menu.click()
        print("✅ Re-opened Station Locator dropdown")

        # Click Fuels
        fuels_link = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//a[normalize-space()="Fuels"]'))
        )
        fuels_link.click()
        print("✅ Clicked 'Fuels'")

        # Click Add Fuel
        add_fuel_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Add fuel"]]'))
        )
        add_fuel_button.click()
        print("✅ Clicked 'Add fuel'")

        # Enter fuel name
        fuel_name_input = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Enter" and @name="name"]'))
        )
        fuel_name_input.send_keys("FUEL MARJORIE")
        print("✅ Entered fuel name")

        # Click Save
        save_button = driver.find_element(By.XPATH, '//button[.//span[text()="Save"]]')
        save_button.click()
        print("✅ Clicked 'Save'")

        # Handle duplicate name error modal (optional)
        try:
            close_icon = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, '//i[contains(@class,"ant-notification-close-icon")]'))
            )
            close_icon.click()
            print("⚠️ Fuel name already exists. Closed error notification.")
        except:
            print("✅ Fuel created successfully or no error appeared.")

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

        # Confirm Cancel with Yes
        yes_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="Yes"]]'))
        )
        yes_button.click()
        print("✅ Confirmed cancel with 'Yes'")



        # 11. Wait before closing
        print("⏳ Waiting 10 seconds before closing browser...")
        time.sleep(10)

    except Exception as e:
        print(f"❌ Test failed: {e}")
    finally:
        if driver:
            driver.quit()
            print("🧹 Browser closed")

if __name__ == "__main__":
    test_station_locator()
