"""Automated Browser Navigation & E2E Verification Script for DSCons ERP."""

import asyncio
import json
import sys
from pathlib import Path

from playwright.async_api import async_playwright

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

SCREENSHOTS_DIR = Path("reports/screenshots")
SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)

BASE_URL = "http://127.0.0.1:8000"


async def run_browser_tests():
    print("================================================================")
    print("  DSCons ERP - Automated Browser Navigation & E2E Testing Suite")
    print("================================================================")
    print(f"Target URL: {BASE_URL}")

    results = []

    async with async_playwright() as p:
        # Launch Chromium headless with standard enterprise desktop viewport
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={"width": 1440, "height": 900},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 DSConsE2E",
        )
        page = await context.new_page()

        # Step 1: Real User Login via Login UI
        print("\n[Step 1] Navigating to /login and authenticating as SuperAdmin...")
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.screenshot(path=str(SCREENSHOTS_DIR / "00_login_page.png"))

        # Click SuperAdmin quick fill button
        await page.click("button:has-text('SuperAdmin')")
        # Wait for redirection to /dashboard
        await page.wait_for_url("**/dashboard", timeout=8000)
        await page.wait_for_timeout(1000)
        print(f"  -> Successfully logged in. Landed on URL: {page.url}")

        # Step 2: Navigate to Main Dashboard (/dashboard)
        print("\n[Step 2] Testing ERP Homepage (/dashboard)...")
        await page.goto(f"{BASE_URL}/dashboard", wait_until="networkidle")
        await page.wait_for_timeout(1000)
        print(f"  -> Landed on URL: {page.url}")
        page_title = await page.title()
        print(f"  -> Page title: {page_title}")

        # Check Sidebar existence and items
        sidebar = await page.query_selector("#erp-sidebar")
        if not sidebar:
            body_html = await page.evaluate("document.body.innerHTML")
            print(f"  -> [DEBUG] Body HTML first 500 chars: {body_html[:500]}")
        assert sidebar is not None, (
            f"Left Sidebar #erp-sidebar must exist on /dashboard, currently on {page.url}"
        )
        print("  [OK] Left Sidebar (#erp-sidebar) is rendered.")

        topbar = await page.query_selector(".erp-topbar")
        assert topbar is not None, "Topbar .erp-topbar must exist on /dashboard"
        print("  [OK] Topbar (.erp-topbar) is rendered.")

        # Verify all nav items
        nav_links = await page.eval_on_selector_all(
            ".erp-sidebar__link",
            "elements => elements.map(el => ({ text: el.textContent.trim(), href: el.getAttribute('href') }))",
        )
        print(f"  -> Found {len(nav_links)} navigation links in sidebar:")
        for idx, l in enumerate(nav_links, 1):
            print(f"     {idx}. {l['text']} -> {l['href']}")

        # Screenshot Dashboard
        ss_path = SCREENSHOTS_DIR / "01_dashboard_home.png"
        await page.screenshot(path=str(ss_path))
        print(f"  [OK] Screenshot captured: {ss_path}")
        results.append(
            {
                "page": "Dashboard",
                "url": "/dashboard",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )

        # Step 3: Test Sidebar Collapsible Toggle
        print("\n[Step 3] Testing Sidebar Collapsible Toggle...")
        toggle_btn = await page.query_selector("#sidebar-toggle-btn")
        if toggle_btn:
            await toggle_btn.click()
            await page.wait_for_timeout(500)
            is_collapsed = await page.evaluate(
                "document.body.classList.contains('sidebar-collapsed')"
            )
            print(f"  -> Clicked toggle: sidebar-collapsed = {is_collapsed}")
            assert is_collapsed, (
                "Body should have 'sidebar-collapsed' class after toggle click"
            )
            await toggle_btn.click()
            await page.wait_for_timeout(500)
            is_expanded = not (
                await page.evaluate(
                    "document.body.classList.contains('sidebar-collapsed')"
                )
            )
            print(f"  -> Clicked toggle again: sidebar expanded = {is_expanded}")
            print("  [OK] Sidebar toggle collapse/expand works perfectly.")

        # Step 4: Test Projects Dashboard (/dashboard/projects)
        print("\n[Step 4] Navigating to Dự Án & WBS (/dashboard/projects)...")
        await page.click("a[data-nav-path='/dashboard/projects']")
        await page.wait_for_url("**/dashboard/projects", timeout=5000)
        await page.wait_for_timeout(1000)
        curr_url = page.url
        print(f"  -> Current URL: {curr_url}")
        active_link = await page.query_selector(".erp-sidebar__link.active")
        active_text = (
            (await active_link.text_content()).strip() if active_link else "None"
        )
        print(f"  -> Active Sidebar Link: {active_text}")
        assert "Dự Án" in active_text, f"Active link should be Dự Án, got {active_text}"
        ss_path = SCREENSHOTS_DIR / "02_projects_dashboard.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Dự Án & WBS",
                "url": "/dashboard/projects",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Projects dashboard navigation verified.")

        # Step 5: Test Quality Dossier Readiness (/dashboard/readiness)
        print("\n[Step 5] Navigating to Hồ Sơ Chất Lượng (/dashboard/readiness)...")
        await page.click("a[data-nav-path='/dashboard/readiness']")
        await page.wait_for_url("**/dashboard/readiness", timeout=5000)
        await page.wait_for_timeout(1000)
        curr_url = page.url
        print(f"  -> Current URL: {curr_url}")
        active_link = await page.query_selector(".erp-sidebar__link.active")
        active_text = (
            (await active_link.text_content()).strip() if active_link else "None"
        )
        print(f"  -> Active Sidebar Link: {active_text}")
        assert "Hồ Sơ" in active_text, f"Active link should be Hồ Sơ, got {active_text}"
        ss_path = SCREENSHOTS_DIR / "03_readiness_dashboard.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Hồ Sơ Chất Lượng",
                "url": "/dashboard/readiness",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Readiness dashboard navigation verified.")

        # Step 6: Test Documents Dashboard (/dashboard/documents)
        print("\n[Step 6] Navigating to Quản Lý Văn Bản (/dashboard/documents)...")
        await page.click("a[data-nav-path='/dashboard/documents']")
        await page.wait_for_url("**/dashboard/documents", timeout=5000)
        await page.wait_for_timeout(1000)
        curr_url = page.url
        print(f"  -> Current URL: {curr_url}")
        active_link = await page.query_selector(".erp-sidebar__link.active")
        active_text = (
            (await active_link.text_content()).strip() if active_link else "None"
        )
        print(f"  -> Active Sidebar Link: {active_text}")
        assert "Văn Bản" in active_text, (
            f"Active link should be Văn Bản, got {active_text}"
        )
        ss_path = SCREENSHOTS_DIR / "04_documents_dashboard.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Quản Lý Văn Bản",
                "url": "/dashboard/documents",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Documents dashboard navigation verified.")

        # Step 7: Test Employees Dashboard (/dashboard/employees)
        print("\n[Step 7] Navigating to Nhân Lực & Ca Máy (/dashboard/employees)...")
        await page.click("a[data-nav-path='/dashboard/employees']")
        await page.wait_for_url("**/dashboard/employees", timeout=5000)
        await page.wait_for_timeout(1000)
        curr_url = page.url
        print(f"  -> Current URL: {curr_url}")
        active_link = await page.query_selector(".erp-sidebar__link.active")
        active_text = (
            (await active_link.text_content()).strip() if active_link else "None"
        )
        print(f"  -> Active Sidebar Link: {active_text}")
        assert "Nhật Ký" in active_text or "Nhân Lực" in active_text, (
            f"Active link should be Nhân Lực, got {active_text}"
        )
        ss_path = SCREENSHOTS_DIR / "05_employees_dashboard.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Nhân Lực & Ca Máy",
                "url": "/dashboard/employees",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Employees dashboard navigation verified.")

        # Step 8: Test Users & RBAC Management (/dashboard/users)
        print("\n[Step 8] Navigating to Quản Trị Phân Quyền (/dashboard/users)...")
        await page.click("a[href='/dashboard/users']")
        await page.wait_for_url("**/dashboard/users", timeout=5000)
        await page.wait_for_timeout(1000)
        curr_url = page.url
        print(f"  -> Current URL: {curr_url}")
        active_link = await page.query_selector(".erp-sidebar__link.active")
        active_text = (
            (await active_link.text_content()).strip() if active_link else "None"
        )
        print(f"  -> Active Sidebar Link: {active_text}")
        assert "Phân Quyền" in active_text or "Quản Trị" in active_text, (
            f"Active link should be Phân Quyền, got {active_text}"
        )
        ss_path = SCREENSHOTS_DIR / "06_users_dashboard.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Quản Trị Phân Quyền",
                "url": "/dashboard/users",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Users & RBAC dashboard navigation verified.")

        # Step 9: Test In-Page Tab Navigation (#equipment and #finance)
        print("\n[Step 9] Testing In-Page Tab Navigation (/dashboard#equipment)...")
        await page.click("a[data-nav-path='/dashboard#equipment']")
        await page.wait_for_url("**/dashboard#equipment", timeout=5000)
        await page.wait_for_timeout(1000)
        is_equip_visible = await page.eval_on_selector(
            "#panel-equipment", "el => !el.classList.contains('hidden')"
        )
        is_fin_hidden = await page.eval_on_selector(
            "#panel-finance", "el => el.classList.contains('hidden')"
        )
        print(
            f"  -> Tab #equipment check: equipVisible={is_equip_visible}, finHidden={is_fin_hidden}"
        )
        assert is_equip_visible, (
            "Equipment panel should be visible when navigating to #equipment"
        )
        ss_path = SCREENSHOTS_DIR / "07_equipment_tab.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Danh Mục Xe Máy",
                "url": "/dashboard#equipment",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Equipment tab switching verified.")

        print("\n[Step 10] Testing Finance Tab Navigation (/dashboard#finance)...")
        await page.click("a[data-nav-path='/dashboard#finance']")
        await page.wait_for_timeout(800)
        is_fin_visible = await page.eval_on_selector(
            "#panel-finance", "el => !el.classList.contains('hidden')"
        )
        is_equip_hidden = await page.eval_on_selector(
            "#panel-equipment", "el => el.classList.contains('hidden')"
        )
        print(
            f"  -> Tab #finance check: finVisible={is_fin_visible}, equipHidden={is_equip_hidden}"
        )
        assert is_fin_visible, (
            "Finance panel should be visible when navigating to #finance"
        )
        ss_path = SCREENSHOTS_DIR / "08_finance_tab.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Dòng Tiền & Tạm Ứng",
                "url": "/dashboard#finance",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Finance tab switching verified.")

        # Step 11: Test User Account Menu Dropdown
        print("\n[Step 11] Testing User Account Dropdown Menu...")
        user_menu = await page.query_selector("#user-menu-trigger")
        assert user_menu is not None, "User menu trigger #user-menu-trigger must exist"
        await user_menu.click()
        await page.wait_for_timeout(500)
        dropdown_display = await page.eval_on_selector(
            "#user-dropdown", "el => el.style.display"
        )
        print(f"  -> User dropdown display: {dropdown_display}")
        assert dropdown_display == "block", (
            "User dropdown should be displayed as block when clicked"
        )
        ss_path = SCREENSHOTS_DIR / "09_user_dropdown.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "User Dropdown",
                "url": "/dashboard",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] User dropdown menu verified.")

        # Step 12: Test Mobile Viewport (iPhone 12 Pro Max: 428x926)
        print(
            "\n[Step 12] Testing Mobile Viewport & Bottom Dock (iPhone 12 Pro Max 428x926)..."
        )
        await page.set_viewport_size({"width": 428, "height": 926})
        await page.wait_for_timeout(500)
        mobile_dock = await page.query_selector(".erp-mobile-dock")
        assert mobile_dock is not None, (
            "Mobile Bottom Dock must exist on mobile screens"
        )
        dock_items = await page.eval_on_selector_all(
            ".erp-dock-item",
            "elements => elements.map(el => ({ text: el.textContent.trim(), href: el.getAttribute('href') }))",
        )
        print(f"  -> Found {len(dock_items)} mobile dock items:")
        for idx, item in enumerate(dock_items, 1):
            print(f"     {idx}. {item['text']} -> {item['href']}")
        ss_path = SCREENSHOTS_DIR / "10_mobile_viewport_dock.png"
        await page.screenshot(path=str(ss_path))
        results.append(
            {
                "page": "Mobile Dock",
                "url": "/dashboard",
                "status": "PASS",
                "screenshot": str(ss_path),
            }
        )
        print("  [OK] Mobile Bottom Dock verified.")

        await context.close()
        await browser.close()

    print("\n================================================================")
    print("  ALL BROWSER E2E TESTS COMPLETED WITH 100% SUCCESS!")
    print("================================================================")
    print(json.dumps(results, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    asyncio.run(run_browser_tests())
