package de.avatic.lcc.e2e.pages;

import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.WaitForSelectorState;
import de.avatic.lcc.e2e.testdata.TestCaseInput;

import java.util.logging.Logger;

/**
 * Page Object for the calculation assistant page.
 * Handles part number entry, supplier selection, and calculation creation.
 */
public class AssistantPage extends BasePage {

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

    // Selectors - using more robust selectors
    private static final String PART_NUMBER_INPUT = "textarea";  // simplified - typically only one textarea on the page
    private static final String ANALYZE_BUTTON_TEXT = "Analyze input";
    private static final String SUPPLIER_SEARCH_INPUT = "input[type='text']";  // fallback, may need refinement
    private static final String LOAD_FROM_PREVIOUS_CHECKBOX = ".checkbox-item";
    private static final String CREATE_CALCULATION_BUTTON_TEXT = "Create";
    private static final String DELETE_SUPPLIER_BUTTON = ".icon-btn";

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

    /**
     * Navigates to the assistant page.
     * The part number modal opens automatically by design.
     */
    public void navigate(String baseUrl) {
        page.navigate(baseUrl + "/assistant");
        waitForSpaNavigation("/assistant");

        // Wait for the part number modal to appear (it opens automatically)
        Locator modal = page.locator(".part-number-modal-container");
        try {
            modal.waitFor(new Locator.WaitForOptions()
                .setState(WaitForSelectorState.VISIBLE)
                .setTimeout(5000));
            logger.info("Part number modal opened automatically");
        } catch (Exception e) {
            logger.info("Modal did not open automatically, will be opened manually when needed");
        }

        // Debug screenshot after navigation
        page.screenshot(new com.microsoft.playwright.Page.ScreenshotOptions()
            .setPath(java.nio.file.Paths.get("target/screenshots/debug_after_navigate.png")));

        logger.info("Navigated to assistant page");
    }

    /**
     * Enters part numbers and clicks analyze.
     * Works with modal whether it's already open or needs to be opened.
     */
    public void searchPartNumbers(String partNumber) {
        // Check if modal is already visible
        Locator modal = page.locator(".part-number-modal-container");
        boolean modalVisible = false;
        try {
            modalVisible = modal.isVisible();
        } catch (Exception e) {
            modalVisible = false;
        }

        if (!modalVisible) {
            // Modal not open, click "Drop part numbers" button to open it
            logger.info("Modal not visible, clicking 'Drop part numbers' button");
            Locator dropButton = page.locator("button:has-text('Drop part numbers')");
            dropButton.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
            dropButton.click();

            // Wait for modal to appear
            modal.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
        } else {
            logger.info("Modal already visible, proceeding with part number entry");
        }

        // Find and fill textarea inside modal - click first to focus, then type
        Locator textarea = modal.locator("textarea");
        textarea.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
        textarea.click();
        page.waitForTimeout(200);
        textarea.fill(partNumber);

        // Debug screenshot after filling
        page.screenshot(new com.microsoft.playwright.Page.ScreenshotOptions()
            .setPath(java.nio.file.Paths.get("target/screenshots/debug_after_fill.png")));

        logger.info(() -> "Filled textarea with: " + partNumber);

        // Click Analyze input button inside modal
        Locator analyzeButton = modal.locator("button:has-text('Analyze input')");
        analyzeButton.click();

        logger.info("Clicked Analyze input button");

        // Wait for modal to close after API response
        page.waitForTimeout(2000);  // Wait for API response

        // Check if modal is still visible and wait for it to close
        try {
            Locator modalOverlay = page.locator(".modal-overlay");
            if (modalOverlay.isVisible()) {
                modalOverlay.waitFor(new Locator.WaitForOptions()
                    .setState(WaitForSelectorState.HIDDEN)
                    .setTimeout(10000));
            }
        } catch (Exception e) {
            logger.warning("Modal overlay check failed: " + e.getMessage());
        }

        // Wait for the part number to appear in the material list (not anywhere on page)
        // The part number appears in: .item-list-element .supplier-item-address
        try {
            Locator partNumberInList = page.locator(".item-list-element .supplier-item-address:has-text('" + partNumber + "')");
            partNumberInList.waitFor(new Locator.WaitForOptions()
                .setState(WaitForSelectorState.VISIBLE)
                .setTimeout(10000));
            logger.info(() -> "Part number " + partNumber + " appeared in the material list");
        } catch (Exception e) {
            logger.warning(() -> "Part number " + partNumber + " not found in material list: " + e.getMessage());
            // Take a screenshot to debug
            page.screenshot(new com.microsoft.playwright.Page.ScreenshotOptions()
                .setPath(java.nio.file.Paths.get("target/screenshots/debug_no_materials.png")));

            // Log what materials are visible
            int itemCount = page.locator(".item-list-element").count();
            logger.info(() -> "Found " + itemCount + " item-list-elements on page");
        }

        logger.info(() -> "Searched for part number: " + partNumber);
    }

    /**
     * Deletes all pre-selected suppliers.
     * Uses specific selector to target only supplier items, not material items.
     * SupplierItem has .supplier-content class with flag, MaterialItem has .material-item-text.
     */
    public void deletePreselectedSuppliers() {
        while (true) {
            try {
                // Target only delete buttons within supplier items (which have .supplier-content)
                // This avoids deleting material items by mistake
                Locator deleteButton = page.locator(".item-list-element:has(.supplier-content) .icon-btn").first();
                deleteButton.waitFor(new Locator.WaitForOptions()
                    .setState(WaitForSelectorState.VISIBLE)
                    .setTimeout(1000));
                deleteButton.click();
                page.waitForTimeout(200);
            } catch (Exception e) {
                // No more supplier delete buttons
                break;
            }
        }
        logger.info("Deleted all pre-selected suppliers");
    }

    /**
     * Selects a supplier by name using autosuggest.
     */
    public void selectSupplier(String supplierName) {
        // Find the search input - look for placeholder text or input near supplier section
        Locator searchInput = page.locator("input[placeholder*='Search'], input[placeholder*='search'], .search-input").first();
        searchInput.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
        searchInput.clear();
        searchInput.fill(supplierName);
        page.waitForTimeout(1000);

        // Click the first suggestion
        Locator suggestion = page.locator(".suggestion-item, .autocomplete-item, [role='option']").first();
        try {
            suggestion.waitFor(new Locator.WaitForOptions()
                .setState(WaitForSelectorState.VISIBLE)
                .setTimeout(3000));
            suggestion.click();
        } catch (Exception e) {
            // Try clicking text that matches the supplier name
            page.getByText(supplierName).first().click();
        }
        page.waitForTimeout(500);
        logger.info(() -> "Selected supplier: " + supplierName);
    }

    /**
     * Sets the "load from previous" checkbox and creates the calculation.
     */
    public void createCalculation(boolean loadFromPrevious) {
        // Try to set checkbox if visible
        try {
            setCheckbox(LOAD_FROM_PREVIOUS_CHECKBOX, loadFromPrevious);
        } catch (Exception e) {
            logger.warning("Could not find load from previous checkbox, continuing...");
        }

        // Use specific role-based selector to avoid matching "Create Calculation" heading
        // and "Create a new supplier" button
        Locator createButton = page.getByRole(AriaRole.BUTTON,
            new Page.GetByRoleOptions().setName("Create").setExact(true));
        createButton.click();

        page.waitForTimeout(500);
        logger.info(() -> "Created calculation with loadFromPrevious: " + loadFromPrevious);
    }

    /**
     * Performs the complete assistant workflow for a test case.
     */
    public void completeAssistantWorkflow(String baseUrl, TestCaseInput input) {
        navigate(baseUrl);
        searchPartNumbers(input.partNumber());
        deletePreselectedSuppliers();
        selectSupplier(input.supplierName());
        createCalculation(input.loadFromPrevious());
    }
}
