package de.nilzbu.mytimetracker.ui.layout;

import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.router.RouterLink;
import com.vaadin.flow.server.VaadinServletRequest;
import com.vaadin.flow.server.VaadinServletResponse;
import de.nilzbu.mytimetracker.ui.view.MainView;
import de.nilzbu.mytimetracker.ui.view.TimeEntryView;
import de.nilzbu.mytimetracker.ui.view.UserManagementView;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

@PermitAll
public class MainLayout extends AppLayout {

    public MainLayout() {
        buildHeader();
    }

    private void buildHeader() {
        H1 title = new H1("Time Tracker");
        title.getStyle()
                .set("font-size", "var(--lumo-font-size-l)")
                .set("margin", "0");

        RouterLink dashboardLink = new RouterLink("Dashboard", MainView.class);
        RouterLink bookingsLink = new RouterLink("Bookings", TimeEntryView.class);
        RouterLink adminLink = new RouterLink("Admin", UserManagementView.class);

        dashboardLink.getStyle().set("margin-left", "2em");
        bookingsLink.getStyle().set("margin-left", "2em");
        adminLink.getStyle().set("margin-left", "2em");

        Button logoutButton = new Button("Logout", event -> performLogout());

        HorizontalLayout headerLayout = new HorizontalLayout(
                title, dashboardLink, bookingsLink, adminLink, logoutButton
        );
        headerLayout.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
        headerLayout.setWidthFull();
        headerLayout.setPadding(true);
        headerLayout.setSpacing(true);

        addToNavbar(headerLayout);
    }

    private void performLogout() {
        HttpServletRequest request = VaadinServletRequest.getCurrent().getHttpServletRequest();
        HttpServletResponse response = VaadinServletResponse.getCurrent().getHttpServletResponse();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }

        getUI().ifPresent(ui -> ui.getPage().setLocation("/login"));
    }
}