package ru.kovbasa.pages;

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

public class PaymentPage {

    private final Page page;

    public PaymentPage(Page page) {
        this.page = page;
    }

    public boolean isOpened() {
        if (page.url().contains("/subscription")) {
            return false;
        }
        if (page.url().contains("payment") || page.url().contains("order")
                || page.url().contains("checkout")) {
            return true;
        }
        return hasPaymentUi();
    }

    public String getPriceText() {
        Locator selected = getSelectedPlanContainer();
        if (selected != null) {
            Locator value = selected.locator("text=/\\d+\\s*₽/");
            if (value.count() > 0) {
                return value.first().textContent().trim();
            }
        }
        Locator pay = page.getByText("К оплате").first();
        if (pay.count() > 0) {
            Locator value = pay.locator("xpath=following::*[contains(text(),'₽')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator sum = page.getByText("Сумма").first();
        if (sum.count() > 0) {
            Locator value = sum.locator("xpath=following::*[contains(text(),'₽')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator price = page.getByText("Стоимость").first();
        if (price.count() > 0) {
            Locator value = price.locator("xpath=following::*[contains(text(),'₽')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator total = page.getByText("Итого").first();
        if (total.count() > 0) {
            Locator value = total.locator("xpath=following::*[contains(text(),'₽')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator priceFallback = page.locator("text=/\\d+\\s*₽/").filter(
                new Locator.FilterOptions().setHasNotText("Скидка")
        ).first();
        if (priceFallback.count() == 0) {
            priceFallback = page.locator("text=/\\d+\\s*руб/").filter(
                    new Locator.FilterOptions().setHasNotText("Скидка")
            ).first();
        }
        return priceFallback.textContent().trim();
    }

    public String getDurationText() {
        Locator selected = getSelectedPlanContainer();
        if (selected != null) {
            Locator value = selected.locator("text=/\\d+\\s+месяц/");
            if (value.count() > 0) {
                return value.first().textContent().trim();
            }
        }
        Locator durationLabel = page.getByText("Продолжительность").first();
        if (durationLabel.count() > 0) {
            Locator value = durationLabel.locator("xpath=following::*[contains(text(),'меся')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator durationAlt = page.getByText("Длительность").first();
        if (durationAlt.count() > 0) {
            Locator value = durationAlt.locator("xpath=following::*[contains(text(),'меся')][1]");
            if (value.count() > 0) {
                return value.textContent().trim();
            }
        }
        Locator durationFallback = page.locator("text=/\\d+\\s+месяц/").first();
        return durationFallback.textContent().trim();
    }

    public void selectTrial() {
        if (!selectPlanByName("Trial")) {
            page.getByText("Trial").first().click(new Locator.ClickOptions().setForce(true));
        }
    }

    public boolean isTrialSelected() {
        Locator trial = page.getByRole(AriaRole.RADIO,
                new Page.GetByRoleOptions().setName("Trial"));
        if (trial.count() > 0) {
            return trial.isChecked();
        }
        Locator aria = page.locator("[role='radio'][aria-checked='true']")
                .filter(new Locator.FilterOptions().setHasText("Trial")).first();
        if (aria.count() > 0) {
            return true;
        }
        return false;
    }

    public boolean selectFirstNonTrial() {
        Locator radios = page.getByRole(AriaRole.RADIO)
                .filter(new Locator.FilterOptions().setHasNotText("Trial"));
        if (radios.count() > 0) {
            radios.first().check();
            return true;
        }
        Locator label = page.locator("label").filter(
                new Locator.FilterOptions().setHasNotText("Trial")
        ).first();
        if (label.count() > 0) {
            label.click(new Locator.ClickOptions().setForce(true));
            return true;
        }
        Locator anyRadio = page.getByRole(AriaRole.RADIO).first();
        if (anyRadio.count() > 0 && !anyRadio.isChecked()) {
            anyRadio.check();
            return true;
        }
        return false;
    }

    public void waitForPlanChange(String oldPrice, String oldDuration) {
        for (int i = 0; i < 10; i++) {
            String price = getPriceText();
            String duration = getDurationText();
            if (!price.equals(oldPrice) || !duration.equals(oldDuration)) {
                return;
            }
            page.waitForTimeout(500);
        }
    }

    private Locator getSelectedPlanContainer() {
        Locator checkedInput = page.locator("input[type='radio']:checked").first();
        if (checkedInput.count() > 0) {
            return checkedInput.locator("xpath=ancestor::*[self::label or self::div or self::li][1]");
        }
        Locator ariaChecked = page.locator("[role='radio'][aria-checked='true']").first();
        if (ariaChecked.count() > 0) {
            return ariaChecked.locator("xpath=ancestor::*[self::label or self::div or self::li][1]");
        }
        return null;
    }

    private boolean hasPaymentUi() {
        if (page.getByText("Оплата").first().isVisible()) {
            return true;
        }
        if (page.getByText("К оплате").first().isVisible()) {
            return true;
        }
        if (page.getByText("Итого").first().isVisible()) {
            return true;
        }
        return page.locator("text=/\\d+\\s*₽/").count() > 0
                || page.getByText("Trial").first().isVisible()
                || page.getByText("Способ оплаты").first().isVisible();
    }

    private boolean selectPlanByName(String name) {
        Locator radio = page.getByRole(AriaRole.RADIO,
                new Page.GetByRoleOptions().setName(name));
        if (radio.count() > 0) {
            radio.check();
            return true;
        }
        Locator label = page.locator("label").filter(
                new Locator.FilterOptions().setHasText(name)
        ).first();
        if (label.count() > 0) {
            label.click(new Locator.ClickOptions().setForce(true));
            return true;
        }
        return false;
    }
}
