package de.assecutor.votianlt.pages.base.ui.view;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.avatar.AvatarVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.component.menubar.MenuBarVariant;
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.Layout;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import de.assecutor.votianlt.pages.view.EditProfileView;
import de.assecutor.votianlt.security.SecurityService;

import static com.vaadin.flow.theme.lumo.LumoUtility.*;

@AnonymousAllowed
@Layout("admin")
public final class AdminLayout extends AppLayout {

    private final SecurityService securityService;
    private Div headerRef;
    private Scroller navRef;
    private Component userMenuRef;

    public AdminLayout(SecurityService securityService) {
        this.securityService = securityService;
        setPrimarySection(Section.DRAWER);

        // Always build the drawer; keep references and toggle visibility on attach and
        // after navigation
        headerRef = createHeader();
        navRef = new Scroller(createSideNav());
        userMenuRef = createUserMenu();
        addToDrawer(headerRef, navRef, userMenuRef);

        updateDrawerVisibility();

        // Re-check on attach (new UI/session) and on every navigation cycle
        addAttachListener(e -> updateDrawerVisibility());
    }

    private void updateDrawerVisibility() {
        boolean loggedIn = securityService.isUserLoggedIn();
        if (headerRef != null)
            headerRef.setVisible(loggedIn);
        if (navRef != null)
            navRef.setVisible(loggedIn);
        if (userMenuRef != null)
            userMenuRef.setVisible(loggedIn);
        setDrawerOpened(loggedIn);
    }

    private Div createHeader() {
        var appLogo = VaadinIcon.SHIELD.create();
        appLogo.addClassNames(TextColor.PRIMARY, IconSize.LARGE);

        var appName = new Span("VotianLT Admin");
        appName.addClassNames(FontWeight.SEMIBOLD, FontSize.LARGE);

        var header = new Div(appLogo, appName);
        header.addClassNames(Display.FLEX, Padding.MEDIUM, Gap.MEDIUM, AlignItems.CENTER);
        return header;
    }

    private Component createSideNav() {
        var nav = new SideNav();
        nav.addClassNames(Margin.Horizontal.MEDIUM);

        // Only admin-specific menu items
        SideNavItem dashboard = new SideNavItem("Dashboard", "admin-dashboard", new Icon(VaadinIcon.DASHBOARD));
        SideNavItem systemSettings = new SideNavItem("Systemeinstellungen", "admin-settings", new Icon(VaadinIcon.COG));
        SideNavItem userManagement = new SideNavItem("Benutzerverwaltung", "admin-users", new Icon(VaadinIcon.USERS));
        SideNavItem systemLogs = new SideNavItem("System-Logs", "admin-logs", new Icon(VaadinIcon.FILE_TEXT));

        nav.addItem(dashboard);
        nav.addItem(systemSettings);
        nav.addItem(userManagement);
        nav.addItem(systemLogs);

        // Create a vertical layout to hold menu items
        VerticalLayout navContainer = new VerticalLayout();
        navContainer.setPadding(false);
        navContainer.setSpacing(false);
        navContainer.add(nav);

        return navContainer;
    }

    private Component createUserMenu() {
        var userMenu = new MenuBar();
        userMenu.addThemeVariants(MenuBarVariant.LUMO_TERTIARY_INLINE);
        userMenu.addClassNames(Margin.MEDIUM);

        // Dynamically updatable components
        var avatar = new Avatar();
        avatar.addThemeVariants(AvatarVariant.LUMO_XSMALL);
        avatar.addClassNames(Margin.Right.SMALL);
        avatar.setColorIndex(1); // Different color for admin

        var userNameSpan = new Span();

        var userMenuItem = userMenu.addItem(avatar);
        userMenuItem.add(userNameSpan);

        // Profile display with navigation
        userMenuItem.getSubMenu().addItem("Profil anzeigen", e -> UI.getCurrent().navigate(EditProfileView.class));
        userMenuItem.getSubMenu().addItem("Admin-Einstellungen");
        userMenuItem.getSubMenu().addItem("Abmelden", e -> securityService.logout());

        // Update function for username and avatar
        Runnable updateUserInfo = () -> {
            String currentUser = securityService.getCurrentUsername();
            avatar.setName(currentUser + " (Admin)");
            userNameSpan.setText(currentUser);
        };

        // Update initially and on attach
        updateUserInfo.run();
        addAttachListener(e -> updateUserInfo.run());

        return userMenu;
    }
}