package ru.kovbasa.pages;

import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
import java.util.List;
import ru.kovbasa.playwright.TestConfig;

public class CorporatePage extends BasePage {

    public CorporatePage(Page page, TestConfig config) {
        super(page, config);
    }

    public void open() {
        openPath("/uslugi-kompaniyam");
    }

    public Page clickLearnMoreInNeedCourseBlock() {
        Locator block = page.locator("section, div")
                .filter(new Locator.FilterOptions().setHasText("Не нашли"))
                .filter(new Locator.FilterOptions().setHasText("курс"))
                .first();
        if (block.count() == 0) {
            block = page.locator("section, div")
                    .filter(new Locator.FilterOptions().setHasText("Не нашли нужный курс"))
                    .first();
        }
        if (block.count() == 0) {
            block = page.locator("section, div")
                    .filter(new Locator.FilterOptions().setHasText("Плана пока нет"))
                    .first();
        }
        if (block.count() == 0) {
            block = page.locator("section, div")
                    .filter(new Locator.FilterOptions().setHasText("Разработка курса"))
                    .first();
        }
        Locator button;
        if (block.count() > 0) {
            block.scrollIntoViewIfNeeded();
            button = block.getByRole(AriaRole.BUTTON,
                    new Locator.GetByRoleOptions().setName("Подробнее")).first();
            if (button.count() == 0) {
                button = block.getByText("Подробнее").first();
            }
            if (button.count() == 0) {
                button = block.getByText("Оставить заявку").first();
            }
            if (button.count() == 0) {
                button = block.locator("a, button").first();
            }
            return clickLearnMoreButton(button);
        }

        Locator candidates = page.locator("a:visible:has-text('Подробнее'),"
                + " button:visible:has-text('Подробнее'),"
                + " a:visible:has-text('Оставить заявку'),"
                + " button:visible:has-text('Оставить заявку')");
        int count = Math.min(candidates.count(), 10);
        for (int i = 0; i < count; i++) {
            Locator candidate = candidates.nth(i);
            Page target = clickLearnMoreButton(candidate);
            CorporatePage targetPage = target == page ? this : new CorporatePage(target, config);
            if (targetPage.isBusinessCoursePageOpened()) {
                return target;
            }
            if (target != page) {
                target.close();
            } else {
                open();
            }
        }
        throw new IllegalStateException("Не найден блок 'Не нашли нужный курс?'");
    }

    public boolean isBusinessCoursePageOpened() {
        Locator heading = page.getByRole(AriaRole.HEADING,
                new Page.GetByRoleOptions().setName("Разработка курса для бизнеса")).first();
        if (heading.count() > 0) {
            heading.waitFor();
            return heading.isVisible();
        }
        if (page.url().contains("razrabotka")
                || page.url().contains("business")) {
            return true;
        }
        if (page.url().contains("/b2b")) {
            return page.getByText("Направления курсов").first().isVisible()
                    || page.getByText("Направления обучения").first().isVisible();
        }
        return false;
    }

    public List<String> getDirections() {
        Locator section = page.locator("section, div").filter(
                new Locator.FilterOptions().setHasText("Направления обучения")
        ).first();
        if (section.count() == 0) {
            section = page.locator("section, div").filter(
                    new Locator.FilterOptions().setHasText("Направления")
            ).first();
        }
        if (section.count() == 0) {
            return page.locator("a:visible").allTextContents();
        }
        return section.locator("a, button, div").allTextContents();
    }

    public DirectionClick clickFirstDirection() {
        Locator section = page.locator("section, div").filter(
                new Locator.FilterOptions().setHasText("Направления обучения")
        ).first();
        if (section.count() == 0) {
            section = page.locator("section, div").filter(
                    new Locator.FilterOptions().setHasText("Направления")
            ).first();
        }
        Locator item = section.count() > 0 ? section.locator("a, button").first()
                : page.locator("a:visible").first();
        String text = item.textContent();
        String href = item.getAttribute("href");
        if (text == null) {
            text = "";
        }
        text = text.trim();
        Page target = clickLearnMoreButton(item);
        String value = (href != null && !href.isBlank()) ? href : text;
        if (href != null && href.contains("/catalog/courses") && target == page
                && target.url().contains("/b2b")) {
            target.navigate(href);
            target.waitForLoadState();
        }
        return new DirectionClick(target, value);
    }

    private Page clickLearnMoreButton(Locator button) {
        Page popup;
        try {
            popup = page.waitForPopup(new Page.WaitForPopupOptions().setTimeout(3000), button::click);
        } catch (RuntimeException ex) {
            popup = null;
        }
        if (popup != null) {
            popup.waitForLoadState();
            return popup;
        }
        try {
            page.waitForNavigation(new Page.WaitForNavigationOptions().setTimeout(5000), button::click);
        } catch (RuntimeException ex) {
            button.click(new Locator.ClickOptions().setForce(true));
        }
        page.waitForLoadState();
        return page;
    }

    public static final class DirectionClick {
        private final Page page;
        private final String value;

        public DirectionClick(Page page, String value) {
            this.page = page;
            this.value = value;
        }

        public Page page() {
            return page;
        }

        public String value() {
            return value;
        }
    }
}
