package de.avatic.lcc.e2e.pages;

import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.WaitForSelectorState;

import java.util.logging.Logger;

/**
 * Page Object for the dev login page (/dev).
 * Allows selecting a user from the dev user table for testing.
 */
public class DevLoginPage extends BasePage {

    private static final Logger logger = Logger.getLogger(DevLoginPage.class.getName());

    private static final String MODAL_YES_BUTTON = "div.modal-dialog-actions button.btn--primary";
    private static final String MODAL_CONTAINER = "div.modal-container";

    public DevLoginPage(Page page) {
        super(page);
    }

    /**
     * Navigates to the dev login page and logs in as the specified user.
     *
     * @param baseUrl  The base URL of the application
     * @param userName The first name of the user to log in as (e.g., "John")
     */
    public void login(String baseUrl, String userName) {
        page.navigate(baseUrl + "/dev");

        // Wait for the page to load
        page.waitForLoadState();

        // The /dev page has two tables. We need the first one (User control tab).
        // Use .first() to get the first table
        Locator userTable = page.locator("table.data-table").first();
        userTable.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));

        // Wait for table rows to appear (API might take time to load data)
        Locator rows = userTable.locator("tbody tr.table-row");
        try {
            rows.first().waitFor(new Locator.WaitForOptions()
                .setState(WaitForSelectorState.VISIBLE)
                .setTimeout(10000));
        } catch (Exception e) {
            logger.warning("No table rows found after waiting. Page content: " +
                page.content().substring(0, Math.min(1000, page.content().length())));
            throw new RuntimeException("No users found in dev user table. Is the API working?", e);
        }

        int rowCount = rows.count();
        logger.info(() -> "Found " + rowCount + " user rows");

        boolean userFound = false;
        for (int i = 0; i < rowCount; i++) {
            Locator row = rows.nth(i);
            Locator firstCell = row.locator("td").first();
            String firstName = firstCell.textContent();

            if (firstName != null && firstName.contains(userName)) {
                row.click();
                userFound = true;
                logger.info(() -> "Selected user: " + userName);
                break;
            }
        }

        if (!userFound) {
            throw new RuntimeException("User '" + userName + "' not found in dev user table");
        }

        // Confirm the login in the modal
        Locator yesButton = page.locator(MODAL_YES_BUTTON);
        yesButton.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
        yesButton.click();

        // Wait for modal to close
        page.locator(MODAL_CONTAINER).waitFor(
            new Locator.WaitForOptions().setState(WaitForSelectorState.HIDDEN)
        );

        logger.info(() -> "Successfully logged in as: " + userName);
    }
}
