import XCTest

final class OverviewCreateUITests: ForgejoReadOnlyUITestBase {

    override func tearDown() {
        navigateBackToHome()
        super.tearDown()
    }

    // MARK: - Create PR from Pull Requests Overview

    @MainActor
    func testCreatePRFromOverview() throws {
        app.tabBars.buttons["Pull Requests"].tap()

        // Default scope is "All involvement", testadmin is assigned to PR #4
        XCTAssertTrue(app.staticTexts["Add feature file"].waitForExistence(timeout: 10))

        // Tap floating create button
        let createButton = app.buttons["pr-create-button"]
        XCTAssertTrue(createButton.waitForExistence(timeout: 10), "Floating create button should exist on Pull Requests overview")
        createButton.tap()

        // Repository picker sheet should appear
        XCTAssertTrue(app.staticTexts["Select Repository"].waitForExistence(timeout: 10), "Repository picker should appear")

        // Select test-repo via accessibility identifier on the button
        let repoButton = app.buttons["repo-picker-testadmin/test-repo"]
        XCTAssertTrue(repoButton.waitForExistence(timeout: 10), "test-repo should appear in the picker")
        repoButton.tap()

        // PR create form should appear with branch pickers after selecting a repo
        XCTAssertTrue(app.staticTexts["New Pull Request"].waitForExistence(timeout: 15), "PR create form should appear after selecting a repo")
        XCTAssertTrue(app.staticTexts["Branches"].waitForExistence(timeout: 10), "Branch picker section should be visible")

        // Cancel and verify we return to the overview
        let cancelButton = app.buttons["Cancel"]
        XCTAssertTrue(cancelButton.waitForExistence(timeout: 5))
        cancelButton.tap()

        XCTAssertTrue(
            app.staticTexts["Add feature file"].waitForExistence(timeout: 10),
            "Should return to PR overview after cancelling"
        )
    }

    // MARK: - Cancel Repository Picker

    @MainActor
    func testCancelRepoPicker() throws {
        app.tabBars.buttons["Issues"].tap()

        // Wait for the floating create button (confirms the overview rendered)
        let createButton = app.buttons["issue-create-button"]
        XCTAssertTrue(createButton.waitForExistence(timeout: 15), "Floating create button should exist on Issues overview")
        createButton.tap()

        // Repository picker sheet should appear
        XCTAssertTrue(app.staticTexts["Select Repository"].waitForExistence(timeout: 10))

        // Cancel
        let cancelButton = app.buttons["Cancel"]
        XCTAssertTrue(cancelButton.waitForExistence(timeout: 5))
        cancelButton.tap()

        // Should return to the issues overview without opening the create form
        XCTAssertTrue(
            createButton.waitForExistence(timeout: 10),
            "Should return to issues overview after cancelling repo picker"
        )
    }
}
