package ru.otus.mobile.screens;

import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import io.appium.java_client.AppiumBy;
import org.openqa.selenium.WebElement;
import ru.otus.mobile.config.AuthContext;
import ru.otus.mobile.config.MobileContext;
import ru.otus.mobile.ui.MobileUi;
import ru.otus.mobile.ui.UiWait;

import static com.codeborne.selenide.Selenide.$;

public class WishlistsScreen {

    public void open() {
        ensureLoggedIn();
        if (MobileUi.existsById("wishlists_content")) {
            return;
        }
        dismissErrorDialogIfPresent();
        if (MobileUi.existsById("mine_menu")) {
            MobileUi.byIdOrAccessibility("mine_menu").click();
        } else if (MobileUi.existsById("go_to_wishlists")) {
            MobileUi.byIdOrAccessibility("go_to_wishlists").click();
        }
    }

    private void dismissErrorDialogIfPresent() {
        if (UiWait.exists(AppiumBy.id("android:id/alertTitle"))
                || UiWait.exists(AppiumBy.id("android:id/message"))) {
            $(AppiumBy.id("android:id/button1")).click();
        }
    }

    public void createWishlist(String name) {
        if (!MobileUi.existsById("add_button")) {
            open();
        }
        MobileUi.byIdOrAccessibility("add_button").click();
        typeInto("title_input", name);
        MobileUi.byIdOrAccessibility("save_button").click();
    }

    public void editWishlist(String oldName, String newName) {
        for (int attempt = 0; attempt < 3; attempt++) {
            if (MobileUi.existsById("wishlists_content")
                    || MobileUi.existsById("wishlist_item")
                    || MobileUi.existsById("list_item")) {
                break;
            }
            MobileUi.back();
        }
        ensureWishlistsList();
        scrollToWishlistTitle(oldName);
        for (int attempt = 0; attempt < 2; attempt++) {
            editButtonFor(oldName).click();
            break;
        }
        typeInto("title_input", newName);
        MobileUi.byIdOrAccessibility("save_button").click();
    }

    public void assertWishlistPresent(String name) {
        scrollToWishlistTitle(name);
    }

    private SelenideElement scrollToWishlistTitle(String name) {
        String pkg = MobileContext.packageName();
        String safe = name.replace("\"", "\\\"");
        String selector = "new UiScrollable(new UiSelector().resourceId(\""
                + pkg + ":id/wishlists\")).scrollIntoView("
                + "new UiSelector().resourceId(\"" + pkg + ":id/title\").textContains(\"" + safe + "\"))";
        try {
            return $(AppiumBy.androidUIAutomator(selector));
        } catch (Exception ignored) {
            String fallback = "new UiScrollable(new UiSelector().scrollable(true)).scrollIntoView("
                    + "new UiSelector().textContains(\"" + safe + "\"))";
            return $(AppiumBy.androidUIAutomator(fallback));
        }
    }

    private SelenideElement editButtonFor(String name) {
        String pkg = MobileContext.packageName();
        String safe = name.replace("\"", "\\\"");
        String xpath = "//androidx.recyclerview.widget.RecyclerView[@resource-id='" + pkg + ":id/wishlists']"
                + "//android.view.ViewGroup[@resource-id='" + pkg + ":id/wishlist_item'"
                + " and .//android.widget.TextView[@resource-id='" + pkg + ":id/title'"
                + " and contains(@text,\"" + safe + "\")]]"
                + "//android.widget.Button[@resource-id='" + pkg + ":id/edit_button']";
        return $(AppiumBy.xpath(xpath));
    }

    public void openWishlistByName(String name) {
        SelenideElement byText = MobileUi.byTextContains(name);
        if (byText.exists()) {
            byText.click();
            return;
        }
        openFirstWishlist();
    }

    public void openFirstWishlist() {
        ElementsCollection items = MobileUi.allById("wishlist_item");
        if (items.isEmpty()) {
            items = MobileUi.allById("list_item");
        }
        items.first().click();
    }

    private void typeInto(String id, String value) {
        WebElement input = MobileUi.byIdOrAccessibility(id)
                .toWebElement();
        input.click();
        input.clear();
        input.sendKeys(value);
    }

    private void ensureWishlistsList() {
        for (int attempt = 0; attempt < 2; attempt++) {
            if (MobileUi.existsById("gifts_content")
                    || MobileUi.existsById("gift_item")) {
                MobileUi.back();
                continue;
            }
            if (MobileUi.existsById("wishlists_content")
                    || MobileUi.existsById("wishlist_item")
                    || MobileUi.existsById("list_item")) {
                return;
            }
            MobileUi.back();
        }
        if (MobileUi.existsById("wishlist_item")
                || MobileUi.existsById("list_item")) {
            return;
        }
        MobileUi.byIdOrAccessibility("wishlists_content");
    }

    private void ensureLoggedIn() {
        LoginScreen loginScreen = new LoginScreen();
        if (!loginScreen.isVisible()) {
            return;
        }
        String username = AuthContext.username();
        String password = AuthContext.password();
        boolean allowRegister = AuthContext.allowRegister();
        if (password == null && username != null) {
            password = "Admin123";
        }
        if (username != null && password != null) {
            loginScreen.loginOrRegister(username, password, allowRegister);
        }
    }
}
