package mx.gob.jumapacelaya.ui;

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.dependency.CssImport;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.Scroller;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.server.menu.MenuConfiguration;
import com.vaadin.flow.theme.lumo.LumoUtility;
import mx.gob.jumapacelaya.services.SecurityService;


@CssImport("./themes/sistema-mantenimiento/styles.css")
public class MainLayout extends AppLayout implements BeforeEnterObserver {

    private H2 viewTitle;
    private  final SecurityService securityService;

    public MainLayout(SecurityService securityService) {
        this.securityService = securityService;
        this.addClassName("app-layout");
        setPrimarySection(Section.DRAWER);
        addDrawerContent();
        addHeaderContent();
    }

    private void addHeaderContent() {
        DrawerToggle toggle = new DrawerToggle();
        toggle.setAriaLabel("Menu toggle");
        toggle.addClassName("drawer-toggle");

        viewTitle = new H2();
        viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);
        viewTitle.getStyle().set("font-weight", "bold");
        viewTitle.getStyle().set("color", "#691B31");
        viewTitle.getStyle().set("font-size", "25px");


        String u = securityService.getAuthenticatedUser();
        Span usrNameLabel = new Span(u);
        //usrNameLabel.getStyle().set("color", "#691b31");
        usrNameLabel.getStyle().set("font-weight", "bold");
        usrNameLabel.getStyle().set("font-size", "20px");

        Button logoutButton = new Button("Cerrar sesión", VaadinIcon.SIGN_OUT.create(),event -> {
            securityService.logout();
        });
        logoutButton.addClassName("logout-button");
        logoutButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY ,ButtonVariant.LUMO_ERROR);

        HorizontalLayout headerContent = new HorizontalLayout();
        headerContent.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
        headerContent.addClassName("header-content");
        headerContent.add(viewTitle);
        headerContent.setFlexGrow(1, viewTitle);
        headerContent.add(usrNameLabel, logoutButton);

        addToNavbar(false, toggle, headerContent);
    }

    private void addDrawerContent() {
        VerticalLayout headerLayout = new VerticalLayout();
        headerLayout.setPadding(true);
        headerLayout.setSpacing(false);
        headerLayout.setAlignItems(FlexComponent.Alignment.CENTER);
        //headerLayout.getStyle().set("background-color", "#DDC9A3");

        Image imgLogo = new Image("images/LOGO_900X160.png", "Logo");
        imgLogo.setWidthFull();

        headerLayout.add(imgLogo);

        Scroller scroller = new Scroller(createNavigation());
        //scroller.getStyle().set("background-color", "#691b31");

        addToDrawer(headerLayout, scroller, createFooter());
    }

    private SideNav createNavigation() {
        SideNav nav = new SideNav();

        nav.addItem(new SideNavItem("Plan Anual", PlanAnualView.class, VaadinIcon.CALENDAR.create()));
        nav.addItem(new SideNavItem("Listado de Actividades", ActDiariaView.class, VaadinIcon.EDIT.create()));
        nav.addItem(new SideNavItem("Mantenimiento Correctivo", MantCorrectivoView.class, VaadinIcon.WRENCH.create()));
        nav.addItem(new SideNavItem("Resultados de Encuestas", ResultEncuestasView.class, VaadinIcon.BAR_CHART_H.create()));
        nav.addItem(new SideNavItem("Preferencias del Sistema", ConfiguracionView.class, VaadinIcon.COG.create()));

        nav.getStyle().set("border-radius", "5px");
        return nav;
    }

    private Footer createFooter() {
        Footer layout = new Footer();

        return layout;
    }

    private String getCurrentPageTitle() {
        return MenuConfiguration.getPageHeader(getContent()).orElse("");
    }

    @Override
    protected void afterNavigation() {
        super.afterNavigation();
        viewTitle.setText(getCurrentPageTitle());
    }

    @Override
    public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
        UI.getCurrent().getPage().executeJs("""
            const theme = localStorage.getItem('appThemePreference');
            if (theme === 'dark') {
                document.documentElement.setAttribute('theme', 'dark');
            } else {
                document.documentElement.removeAttribute('theme');
            }
        """);
    }
}
