package com.example.views;

import com.example.components.Fa;
import com.example.js.CommonJS;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.component.menubar.MenuBarVariant;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
import com.vaadin.flow.router.Layout;
import com.vaadin.flow.server.VaadinSession;

import java.util.Locale;

@Layout
public class MainLayout extends AppLayout {

    private final Button themeToggle = new Button(Fa.MOON.create());

    public MainLayout() {
        DrawerToggle toggle = new DrawerToggle();

        Span title = new Span(getTranslation("app.title"));
        title.addClassName("dialect-title");

        Span spacer = new Span();
        spacer.getStyle().set("flex-grow", "1");

        MenuBar languageMenu = buildLanguageMenu();

        themeToggle.addThemeVariants(ButtonVariant.TERTIARY, ButtonVariant.LUMO_ICON);
        themeToggle.setAriaLabel(getTranslation("action.themeToggle"));
        themeToggle.addClickListener(e ->
                getElement().executeJs(CommonJS.TOGGLE_THEME_JS).then(String.class, this::applyIconFor));

        addToNavbar(toggle, title, spacer, languageMenu, themeToggle);

        getElement().executeJs(CommonJS.INIT_THEME_JS).then(String.class, this::applyIconFor);

        SideNav nav = new SideNav();
        nav.addItem(new SideNavItem(getTranslation("nav.dashboard"), DashboardView.class,
                Fa.DASHBOARD.create()));
        nav.addItem(new SideNavItem(getTranslation("nav.form"), FormView.class,
                Fa.FORM.create()));
        nav.addItem(new SideNavItem(getTranslation("nav.table"), TableView.class,
                Fa.TABLE.create()));

        addToDrawer(nav);
    }

    private MenuBar buildLanguageMenu() {
        MenuBar menuBar = new MenuBar();
        menuBar.addThemeVariants(MenuBarVariant.LUMO_TERTIARY_INLINE);

        var root = menuBar.addItem(Fa.GLOBE.create());
        root.setAriaLabel(getTranslation("action.language"));

        root.getSubMenu().addItem(getTranslation("lang.de"), e -> switchLanguage(Locale.GERMAN));
        root.getSubMenu().addItem(getTranslation("lang.en"), e -> switchLanguage(Locale.ENGLISH));
        root.getSubMenu().addItem(getTranslation("lang.es"), e -> switchLanguage(Locale.of("es")));

        return menuBar;
    }

    private void switchLanguage(Locale locale) {
        VaadinSession.getCurrent().setLocale(locale);
        UI.getCurrent().getPage().reload();
    }

    private void applyIconFor(String theme) {
        themeToggle.setIcon("dark".equals(theme) ? Fa.SUN.create() : Fa.MOON.create());
    }
}
