package dev.fyloz.plannervio.ui.view

import com.jfoenix.controls.JFXButton
import com.jfoenix.controls.JFXTextField
import dev.fyloz.plannervio.core.service.SvgPathName
import dev.fyloz.plannervio.ui.style.Style
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.geometry.Pos
import javafx.scene.layout.Priority
import tornadofx.*

/** The app's main view */
class MainView : AbstractView() {
    private val presenter: MainViewPresenter by inject()

    override val root = borderpane {
        left = vbox {
            addClass(Style.navBar)
            alignment = Pos.TOP_LEFT

            this += label {
                addClass(Style.appNameLabel)
                alignment = Pos.CENTER
                text = "Plannervio"
            }
            this += JFXTextField().apply {
                vgrow = Priority.NEVER
                isLabelFloat = true
                promptText = messages["search"] // TODO
                vboxMargin(horizontal = 16, vertical = 20)
            }
            this += tabButton(Tab.BOARDS, presenter::onTabButtonClick).apply {
                presenter.switchTab(this)   // Default tab
            }
            this += tabButton(Tab.FAVORITES, presenter::onTabButtonClick)
            this += tabButton(Tab.HISTORY, presenter::onTabButtonClick)
            this += tabButton(Tab.SETTINGS, presenter::onTabButtonClick)
        }
    }
}

class MainViewPresenter : Controller() {
    private var activeTabButton: TabButton? = null

    /** Called when a [TabButton] has been clicked. */
    fun onTabButtonClick(button: TabButton) {
        switchTab(button)
    }

    /** Called when the search bar detects changes. Its content is contained in [searchQuery]. */
    fun onSearchChange(searchQuery: String) {
        println(searchQuery)
    }

    /** Switch the active tab to [button]'s tab. */
    fun switchTab(button: TabButton) {
        activeTabButton?.active = false
        button.active = true
        activeTabButton = button
    }
}

/** The [TabButton] is a button linked to a [tab]. */
class TabButton(tab: Tab, active: Boolean = false) : JFXButton() {
    /** Specifies the [Tab] linked to the button. */
    val tabProperty by lazy { SimpleObjectProperty(tab) }
    var tab: Tab by tabProperty

    /** Specifies if the button is active. */
    val activeProperty = SimpleBooleanProperty(this, "active", active)
    var active: Boolean
        get() = activeProperty.get()
        set(value) {
            toggleClass(Style.active, value)
            activeProperty.set(value)
        }
}

enum class Tab(val icon: SvgPathName, val i18nText: String) {
    BOARDS(SvgPathName.FORMAT_LIST_BULLETED, "tab.boards.label"),
    FAVORITES(SvgPathName.STAR, "tab.favorites.label"),
    HISTORY(SvgPathName.HISTORY, "tab.history.label"),
    SETTINGS(SvgPathName.COG, "tab.settings.label")
}
