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

# Import login
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_about_us_card_type():
    driver = None
    try:
        driver = login_to_cms()
        print("✅ Logged in, starting About Us > Card Types test")

        wait = WebDriverWait(driver, 20)

        # Click the 'About Us' dropdown by targeting the div with exact text
        about_us_menu = wait.until(EC.element_to_be_clickable((
            By.XPATH, "//div[contains(@class, 'ant-menu-submenu-title')][.//span[text()='About Us']]"
        )))
        driver.execute_script("arguments[0].click();", about_us_menu)
        print("✅ Clicked on 'About Us' to reveal submenu")


        # Click "Card Types"
        card_types_link = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//a[@href='/about-us/card-types']")))
        card_types_link.click()
        print("✅ Clicked on 'Card Types'")

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

        # Fill Card Code
        card_code_input = wait.until(EC.presence_of_element_located(
            (By.NAME, "code")))
        card_code_input.send_keys("MARJORIECODE")
        print("✅ Inputted Card Code")

        # Fill Card Type Description
        # Find all inputs with name="type"
        type_inputs = wait.until(EC.presence_of_all_elements_located((By.NAME, "type")))

        # Input in the first one: Card Type Description
        type_inputs[0].send_keys("test card description")
        print("✅ Card Type Description input filled")

       # Fill in the Card Type Short Description (textarea with name="description")
        short_desc_textarea = wait.until(EC.presence_of_element_located((By.NAME, "description")))
        short_desc_textarea.send_keys("this is a card type short description")
        print("✅ Card Type Short Description input filled")

        # Upload Card Type Image
        upload_inputs = driver.find_elements(By.CSS_SELECTOR, "input[type='file']")
        if upload_inputs:
            image_path = os.path.abspath(r"C:\\Users\\MARJORIE ANITO\\unioil_testing\\image\\image.jpg")
            upload_inputs[0].send_keys(image_path)
            print("✅ Card Type Image uploaded")
            time.sleep(3)  # wait for upload preview to show
        else:
            print("❌ File input for Card Type Image not found")

        # Select Black radio button
        try:
            black_radio = driver.find_element(By.CSS_SELECTOR, "input[type='radio'][value='2']")
            driver.execute_script("arguments[0].click();", black_radio)
            print("✅ Selected 'Black' radio button")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to select 'Black' radio button: {e}")

        # Upload Card Type Cover
        upload_inputs = driver.find_elements(By.CSS_SELECTOR, "input[type='file']")
        if len(upload_inputs) > 1:
            cover_path = os.path.abspath(r"C:\\Users\\MARJORIE ANITO\\unioil_testing\\image\\image.jpg")
            upload_inputs[1].send_keys(cover_path)
            print("✅ Card Type Cover uploaded")
            time.sleep(3)
        else:
            print("❌ File input for Card Type Cover not found")

        # Add Terms and Conditions
        try:
            terms_textarea = driver.find_element(By.NAME, "terms_and_conditions")
            terms_textarea.clear()
            terms_textarea.send_keys("TESTING")
            print("✅ Terms and Conditions entered")
        except Exception as e:
            print(f"❌ Failed to enter Terms and Conditions: {e}")

        # Add FAQs
        try:
            faqs_textarea = driver.find_element(By.NAME, "faqs")
            faqs_textarea.clear()
            faqs_textarea.send_keys("TESTING")
            print("✅ FAQs entered")
        except Exception as e:
            print(f"❌ Failed to enter FAQs: {e}")

        # Click Submit
        try:
            submit_btn = driver.find_element(By.XPATH, "//button[.//span[text()='Submit']]")
            driver.execute_script("arguments[0].click();", submit_btn)
            print("✅ Submit button clicked")
        except Exception as e:
            print(f"❌ Failed to click Submit button: {e}")

        # After clicking Submit, handle error modal if it appears
        try:
            close_error_icon = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//i[contains(@class, 'ant-notification-close-icon')]"))
            )
            close_error_icon.click()
            print("🟡 Error/notification modal appeared and was closed")

            # Click Cancel to exit the form
            cancel_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Cancel']]"))
            )
            cancel_btn.click()
            print("✅ Cancel button clicked after closing error modal")

            # Click Yes on the confirmation modal
            yes_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Yes']]"))
            )
            yes_btn.click()
            print("✅ Clicked Yes on cancel confirmation after error modal")

            time.sleep(2)
        except TimeoutException:
            print("ℹ️ No error modal appeared, proceeding normally...")

        # Search for PRIVATEB
        try:
            search_input = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input[placeholder='Search']"))
            )
            search_input.clear()
            search_input.send_keys("PRIVATEB")
            search_input.send_keys(Keys.ENTER)
            print("✅ Searched for PRIVATEB")
            time.sleep(3)  # wait for search results
        except Exception as e:
            print(f"❌ Search input error: {e}")

        # Click View icon
        try:
            view_icon = driver.find_element(By.CSS_SELECTOR, "i.anticon-right-circle-o")
            driver.execute_script("arguments[0].click();", view_icon)
            print("✅ View icon clicked")
            time.sleep(2)
        except Exception as e:
            print(f"❌ Failed to click View icon: {e}")

        # Click Delete and then No
        try:
            delete_btn = driver.find_element(By.XPATH, "//button[.//span[text()='Delete']]")
            driver.execute_script("arguments[0].click();", delete_btn)
            print("✅ Delete button clicked")

            no_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='No']]"))
            )
            no_btn.click()
            print("✅ Clicked No on confirmation")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Delete/No click failed: {e}")

        # Click Update and then Cancel
        try:
            update_btn = driver.find_element(By.XPATH, "//button[.//span[text()='Update']]")
            driver.execute_script("arguments[0].click();", update_btn)
            print("✅ Update button clicked")
            time.sleep(2)

            cancel_btn = driver.find_element(By.XPATH, "//button[.//span[text()='Cancel']]")
            cancel_btn.click()
            print("✅ Cancel button clicked")

            yes_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Yes']]"))
            )
            yes_btn.click()
            print("✅ Clicked Yes on cancel confirmation")
        except Exception as e:
            print(f"❌ Update/Cancel sequence failed: {e}")

        # Click Terms & Privacy
        try:
            terms_privacy_link = wait.until(EC.element_to_be_clickable(
                (By.XPATH, "//a[@href='/about-us/term-privacy']")))
            terms_privacy_link.click()
            print("✅ Clicked on 'Terms & Privacy'")
            time.sleep(2)
        except Exception as e:
            print(f"❌ Failed to click 'Terms & Privacy': {e}")

        # Click Add button (dropdown trigger)
        try:
            add_dropdown_btn = wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, "button.terms-management")))
            add_dropdown_btn.click()
            print("✅ Clicked on 'Add' dropdown")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to click 'Add' dropdown: {e}")

        # Click 'Terms & Condition' option
        try:
            terms_option = wait.until(EC.element_to_be_clickable(
                (By.XPATH, "//li[contains(text(), 'Terms & Condition')]")))
            terms_option.click()
            print("✅ Clicked on 'Terms & Condition'")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to select 'Terms & Condition': {e}")

        # Fill in Title
        try:
            title_input = wait.until(EC.presence_of_element_located(
                (By.XPATH, "//input[@name='title']")))
            title_input.clear()
            title_input.send_keys("T&C Title")
            print("✅ Entered T&C Title")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to enter T&C Title: {e}")

        # Fill in Details
        try:
            details_textarea = wait.until(EC.presence_of_element_located(
                (By.XPATH, "//textarea[@name='details']")))
            details_textarea.clear()
            details_textarea.send_keys("T&C Details")
            print("✅ Entered T&C Details")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to enter T&C Details: {e}")

        # Submit the form
        try:
            submit_btn = wait.until(EC.element_to_be_clickable(
                (By.XPATH, "//button[.//span[text()='Submit']]")))
            submit_btn.click()
            print("✅ Submitted T&C form")
            time.sleep(2)
        except TimeoutException as e:
            print(f"❌ Failed to submit T&C form: {e}")
        

               # Click Add button (dropdown trigger) again
        try:
            add_dropdown_btn = wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, "button.terms-management")))
            add_dropdown_btn.click()
            print("✅ Clicked on 'Add' dropdown")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to click 'Add' dropdown: {e}")

        # Select Privacy Policy from the dropdown
        try:
            privacy_policy_option = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//li[.//text()='Privacy Policy']"))
            )
            privacy_policy_option.click()
            print("✅ Selected 'Privacy Policy' from dropdown")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to select 'Privacy Policy' from dropdown: {e}")

        # Add Title for Privacy Policy
        try:
            title_input = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.NAME, "title"))
            )
            title_input.clear()
            title_input.send_keys("PP Title")
            print("✅ Inputted Privacy Policy Title")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to input Privacy Policy Title: {e}")

        # Add Details for Privacy Policy
        try:
            details_textarea = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.NAME, "details"))
            )
            details_textarea.clear()
            details_textarea.send_keys("PP Details")
            print("✅ Inputted Privacy Policy Details")
            time.sleep(1)
        except Exception as e:
            print(f"❌ Failed to input Privacy Policy Details: {e}")

        # Submit the form for Privacy Policy
        try:
            submit_btn = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Submit']]"))
            )
            submit_btn.click()
            print("✅ Submitted Privacy Policy form")
            time.sleep(2)
        except TimeoutException as e:
            print(f"❌ Failed to submit Privacy Policy form: {e}")

        

        print("🎉 Test completed successfully")

    except Exception as e:
        print(f"❌ Test failed: {e}")
    finally:
        if driver:
            print("🔒 Closing the browser in 10 seconds...")
            time.sleep(10)
            driver.quit()

if __name__ == "__main__":
    test_about_us_card_type()
