import pytest
import playwright.sync_api
from playwright.sync_api import expect
import random


def test_folder_deletion_and_resync_flow(playwright: playwright.sync_api.Playwright):
    """
    Test the complete folder deletion and resync flow:
    1. Navigate to localhost:5001
    2. Create a new user
    3. Configure IMAP with specified details
    4. Sync folders and verify they exist
    5. Delete all folders
    6. Verify folders are deleted
    7. Resync folders
    8. Verify folders reappear
    """
    
    # Launch browser
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    
    try:
        # Generate unique data for this test run
        random_number = random.randint(1000, 9999)
        test_email = f"testuser{random_number}@example.com"
        test_username = f"user{random_number}"
        
        # Step 1: Navigate to localhost:5000 (login page)
        page.goto("http://localhost:5001")
        
        # Wait for page to load
        page.wait_for_load_state("networkidle")

        # Step 2: Navigate to signup page
        # Click the "Sign up" link
        page.click("a:has-text('Sign up')")
        
        # Wait for navigation to complete
        page.wait_for_load_state("networkidle")

        # Step 3: Create a new user
        # Fill out signup form
        page.fill("input[name='first_name']", "Test")
        page.fill("input[name='last_name']", "User")
        page.fill("input[name='email']", test_email)
        page.fill("input[name='password']", "TestPassword123")
        page.fill("input[name='confirm_password']", "TestPassword123")
        page.check("input[name='terms']")
        
        # Submit signup form
        page.click("button:has-text('Create Account')")
        
        # Wait for navigation to complete
        page.wait_for_load_state("networkidle")
        
        # Step 4: Configure IMAP
        # Wait for and click the "Configure IMAP" button
        configure_button = page.locator("button:has-text('Configure IMAP')")
        configure_button.click()
        
        # Wait for modal to appear
        page.wait_for_selector("#imap-modal")
        
        # Fill out IMAP configuration form
        page.fill("input[name='server']", "localhost")
        page.fill("input[name='port']", "5143")
        page.fill("input[name='username']", "user1@example.com")
        page.fill("input[name='password']", "password1")
        
        # Uncheck SSL checkbox
        page.uncheck("input[name='use_ssl']")
        
        # Submit IMAP configuration form
        page.click("button[type='submit']")
        
        # Wait for connection test to complete
        page.wait_for_selector("h3:has-text('Configure IMAP Folders')")
        
        # Step 5: Click "Save and Continue" on the final modal
        page.click("button:has-text('Save and Continue')")
        
        # Wait for modal to close and navigation to complete
        page.wait_for_load_state("networkidle")
        
        # Wait for modal to close and navigation to complete
        page.wait_for_load_state("networkidle")
        
        # Wait for modal to appear and folders to sync
        page.wait_for_selector("#folders-list", timeout=10000)
        
        # Wait for at least 3 folder cards to be visible (based on existing test)
        page.wait_for_function("document.querySelectorAll('.card.bg-base-100.shadow-xl').length >= 3", timeout=15000)
        
        # Get the count of folder cards
        folder_cards_before = page.locator(".card.bg-base-100.shadow-xl")
        count_before = folder_cards_before.count()
        print(f"Found {count_before} folder cards before deletion")
        
        # Verify we have at least 3 folder cards
        assert count_before >= 3, f"Expected at least 3 folder cards, but found {count_before}"
        
        # Step 6: Delete all folders
        # Find all delete buttons for folders
        delete_buttons = page.locator(".delete-button")
        
        print(f"Found {delete_buttons.count()} folders to delete")
        
        # Click each delete button to delete all folders
        while delete_buttons.count() > 0:
            # Get the delete button and click it
            delete_button = delete_buttons.nth(0)
            delete_button.click()
            
            # Wait for the deletion to process and UI to update
            page.wait_for_timeout(1000)  # Small delay to allow processing
            page.on('dialog', lambda dialog:  dialog.accept())
            # Wait for the folder card to be removed from the DOM
            page.wait_for_load_state("networkidle")
            delete_buttons = page.locator(".delete-button")
        
        # Wait for final state to settle
        
        # Step 7: Verify folders are deleted
        folder_cards_after_delete = page.locator(".card.bg-base-100.shadow-xl")
        count_after_delete = folder_cards_after_delete.count()
        print(f"Found {count_after_delete} folder cards after deletion")
        
        # Verify all folders are deleted
        assert count_after_delete == 0, f"Expected 0 folder cards after deletion, but found {count_after_delete}"
        
    finally:
        # Close browser
        browser.close()