from django.test import tag
from lariv.testing import LarivUITestCase
from selenium.webdriver.common.by import By


@tag("ui")
class UserUITest(LarivUITestCase):
    """UI tests for the Users app."""

    def test_user_full_crud_flow(self):
        """Test full CRUD flow for Users using only UI navigation."""
        try:
            self.login()

            # 1. Navigate to Users List
            self.click_link_by_text("Users")
            self.wait_for_htmx()
            # Wait for sidebar link to be clickable
            self.find_clickable(By.XPATH, "//a[contains(., 'All Users')]")
            self.click_link_by_text("All Users")
            self.wait_for_htmx()

            self.assert_text_present("User List")

            # 2. Create User
            self.click_link_by_text("Create User")
            self.wait_for_htmx()

            # Wait for form to be visible
            self.find_visible(By.NAME, "name")

            user_email = "newuser@example.com"
            self.fill_form(
                {"name": "New Test User", "email": user_email, "phone": "1111111111"}
            )
            self.submit_htmx_form()

            # Verify detail
            self.wait_for_url_matches(r"/app/users/\d+/")
            self.assert_text_present("New Test User")
            self.assert_text_present(user_email)

            self.wait_for_htmx()

            # 3. Edit User
            edit_link = self.find_clickable(
                By.XPATH, "//a[contains(normalize-space(), 'Edit User')]"
            )
            self.driver.execute_script("arguments[0].click();", edit_link)
            self.wait_for_htmx()
            self.assert_text_present("Edit User")

            # Wait for form to be visible
            self.find_visible(By.NAME, "name")

            self.fill_input("name", "New Test User Updated")
            self.submit_htmx_form()
            self.wait_for_htmx()

            # Verify update
            self.assert_text_present("New Test User Updated")

            # 4. Delete User
            self.click_htmx_link(By.CSS_SELECTOR, "a[hx-get*='/delete/']")
            self.wait_for_htmx()

            self.assert_text_present("Confirm Deletion")
            self.click_htmx_link(By.XPATH, "//button[contains(., 'Confirm Delete')]")

            # Verify redirect back to list
            self.wait_for_htmx()
            self.assert_text_present("User List")
            self.assert_text_not_present(user_email)
        except Exception as e:
            self.print_page_source()
            print(e)
            raise e
