package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.icon.Icon;
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.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.AppDevice;
import de.assecutor.votianlt.model.AppUser;
import de.assecutor.votianlt.pages.service.AppDeviceService;
import de.assecutor.votianlt.pages.service.AppUserService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;

@PageTitle("Endgeräte")
@Route(value = "app-devices", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class AppDevicesView extends VerticalLayout {

    private final AppDeviceService appDeviceService;
    @SuppressWarnings("unused") // Wird in Grid-Spalte verwendet
    private final AppUserService appUserService;
    private final Grid<AppDevice> appDeviceGrid;

    @Autowired
    public AppDevicesView(AppDeviceService appDeviceService, AppUserService appUserService) {
        this.appDeviceService = appDeviceService;
        this.appUserService = appUserService;

        setSizeFull();
        setPadding(true);
        setSpacing(true);

        // Header mit Titel und Button
        HorizontalLayout header = new HorizontalLayout();
        header.setWidthFull();
        header.setAlignItems(FlexComponent.Alignment.CENTER);

        H2 title = new H2("Endgeräte");
        title.getStyle().set("margin", "0");

        Button addButton = new Button("Neues Endgerät anlegen", new Icon(VaadinIcon.PLUS));
        addButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        addButton.addClickListener(e -> navigateToAddAppDevice());

        header.add(title, addButton);
        header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN);
        add(header);

        // Grid für Endgeräte
        appDeviceGrid = new Grid<>(AppDevice.class, false);
        appDeviceGrid.setSizeFull();

        // Grid-Spalten konfigurieren
        appDeviceGrid.addColumn(AppDevice::getName).setHeader("Gerätename").setAutoWidth(true);

        // App-Nutzer Spalte mit Name anzeigen
        appDeviceGrid.addColumn(appDevice -> {
            if (appDevice.getAppUserId() != null) {
                try {
                    AppUser appUser = appUserService.findByCurrentUser().stream()
                            .filter(user -> user.getId().equals(appDevice.getAppUserId())).findFirst().orElse(null);
                    if (appUser != null) {
                        return appUser.getVorname() + " " + appUser.getNachname();
                    }
                } catch (Exception e) {
                    // Fehler beim Laden des App-Nutzers ignorieren
                }
            }
            return "Nicht zugeordnet";
        }).setHeader("Zugeordneter App-Nutzer").setAutoWidth(true);

        appDeviceGrid.addColumn(AppDevice::getErstelltAm).setHeader("Erstellt am").setAutoWidth(true);

        // Make grid rows clickable
        appDeviceGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
        appDeviceGrid.getStyle().set("cursor", "pointer");

        // Add click listener to navigate to edit view
        appDeviceGrid.addItemClickListener(event -> {
            AppDevice appDevice = event.getItem();
            if (appDevice != null && appDevice.getId() != null) {
                getUI().ifPresent(ui -> ui.navigate("edit-app-device/" + appDevice.getId().toHexString()));
            }
        });

        add(appDeviceGrid);

        // Daten laden
        loadAppDevices();
    }

    private void loadAppDevices() {
        var appDevices = appDeviceService.findByCurrentUser();
        appDeviceGrid.setItems(appDevices);
    }

    private void navigateToAddAppDevice() {
        getUI().ifPresent(ui -> ui.navigate("add-app-device"));
    }
}
