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.combobox.ComboBox;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.notification.Notification;
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.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.HasUrlParameter;
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.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;

@PageTitle("Endgerät bearbeiten")
@Route(value = "edit-app-device", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class EditAppDeviceView extends VerticalLayout implements HasUrlParameter<String> {

    private final AppDeviceService appDeviceService;
    private final AppUserService appUserService;
    private final Binder<AppDevice> binder;

    // Formularfelder
    private final TextField nameField;
    private final ComboBox<AppUser> appUserComboBox;

    // Aktuelles Endgerät
    private AppDevice currentAppDevice;

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

        // Binder initialisieren
        binder = new Binder<>(AppDevice.class);

        // Formularfelder erstellen
        nameField = new TextField("Gerätename");
        nameField.setRequired(true);
        nameField.setPlaceholder("z.B. iPhone 15, Samsung Galaxy S24");
        nameField.setWidth("100%");

        // AppUser ComboBox
        appUserComboBox = new ComboBox<>("App-Nutzer zuordnen");
        appUserComboBox.setPlaceholder("App-Nutzer auswählen (optional)");
        appUserComboBox.setWidth("100%");
        appUserComboBox.setItemLabelGenerator(
                appUser -> appUser.getVorname() + " " + appUser.getNachname() + " (" + appUser.getEmail() + ")");

        // Lade verfügbare App-Nutzer
        try {
            appUserComboBox.setItems(appUserService.findByCurrentUser());
        } catch (Exception e) {
            Notification.show("Fehler beim Laden der App-Nutzer: " + e.getMessage(), 3000,
                    Notification.Position.MIDDLE);
        }

        // Layout konfigurieren
        setSizeFull();
        setPadding(true);
        setSpacing(true);

        // Content zentrieren
        setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);

        // Hauptcontainer erstellen
        VerticalLayout contentContainer = new VerticalLayout();
        contentContainer.setWidth("600px");
        contentContainer.setMaxWidth("90%");
        contentContainer.getStyle().set("background", "var(--lumo-base-color)");
        contentContainer.getStyle().set("border-radius", "8px");
        contentContainer.getStyle().set("box-shadow", "0 2px 8px rgba(0,0,0,0.1)");
        contentContainer.setPadding(true);
        contentContainer.setSpacing(true);

        // Titel
        H2 title = new H2("Endgerät bearbeiten");
        title.getStyle().set("margin", "0");
        title.getStyle().set("text-align", "center");
        contentContainer.add(title);

        // Formular
        FormLayout formLayout = new FormLayout();
        formLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1));
        formLayout.add(nameField, appUserComboBox);
        contentContainer.add(formLayout);

        // Buttons
        HorizontalLayout buttonLayout = new HorizontalLayout();
        buttonLayout.setWidthFull();
        buttonLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        buttonLayout.setSpacing(true);

        Button backButton = new Button("Zurück");
        backButton.addClickListener(e -> navigateBack());

        Button saveButton = new Button("Speichern");
        saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        saveButton.addClickListener(e -> saveAppDevice());

        Button deleteButton = new Button("Löschen");
        deleteButton.addThemeVariants(ButtonVariant.LUMO_ERROR);
        deleteButton.addClickListener(e -> deleteAppDevice());

        buttonLayout.add(backButton, saveButton, deleteButton);
        contentContainer.add(buttonLayout);

        add(contentContainer);

        // Binder konfigurieren
        setupBinder();
    }

    @Override
    public void setParameter(com.vaadin.flow.router.BeforeEvent event, String parameter) {
        try {
            ObjectId deviceId = new ObjectId(parameter);
            loadAppDevice(deviceId);
        } catch (IllegalArgumentException e) {
            Notification.show("Ungültige Endgerät-ID", 3000, Notification.Position.MIDDLE);
            navigateBack();
        }
    }

    private void loadAppDevice(ObjectId deviceId) {
        currentAppDevice = appDeviceService.findById(deviceId);

        if (currentAppDevice != null) {
            // Formular mit aktuellen Daten füllen
            binder.readBean(currentAppDevice);
        } else {
            Notification.show("Endgerät nicht gefunden", 3000, Notification.Position.MIDDLE);
            navigateBack();
        }
    }

    private void setupBinder() {
        binder.forField(nameField).asRequired("Gerätename ist erforderlich").bind(AppDevice::getName,
                AppDevice::setName);

        binder.forField(appUserComboBox).bind(appDevice -> {
            if (appDevice.getAppUserId() != null) {
                return appUserService.findByCurrentUser().stream()
                        .filter(user -> user.getId().equals(appDevice.getAppUserId())).findFirst().orElse(null);
            }
            return null;
        }, (appDevice, appUser) -> {
            if (appUser != null) {
                appDevice.setAppUserId(appUser.getId());
            } else {
                appDevice.setAppUserId(null);
            }
        });
    }

    private void saveAppDevice() {
        if (binder.validate().isOk()) {
            try {
                // Aktuelle Daten in das Modell schreiben
                binder.writeBean(currentAppDevice);

                // Endgerät aktualisieren
                AppDevice updatedDevice = appDeviceService.updateAppDevice(currentAppDevice);

                Notification.show("Endgerät erfolgreich aktualisiert: " + updatedDevice.getName(), 3000,
                        Notification.Position.MIDDLE);

                // Zurück zur Übersicht
                navigateBack();

            } catch (Exception e) {
                Notification.show("Fehler beim Aktualisieren des Endgeräts: " + e.getMessage(), 5000,
                        Notification.Position.MIDDLE);
            }
        } else {
            Notification.show("Bitte füllen Sie alle erforderlichen Felder aus", 3000, Notification.Position.MIDDLE);
        }
    }

    private void deleteAppDevice() {
        if (currentAppDevice != null && currentAppDevice.getId() != null) {
            ConfirmDialog confirmDialog = new ConfirmDialog();
            confirmDialog.setHeader("Endgerät löschen");
            confirmDialog.setText("Möchten Sie das Endgerät \"" + currentAppDevice.getName() + "\" wirklich löschen?");
            confirmDialog.setCancelText("Abbrechen");
            confirmDialog.setConfirmText("Löschen");
            confirmDialog.setConfirmButtonTheme("error primary");

            confirmDialog.addConfirmListener(event -> {
                try {
                    appDeviceService.deleteById(currentAppDevice.getId());
                    Notification.show("Endgerät erfolgreich gelöscht", 3000, Notification.Position.MIDDLE);
                    navigateBack();
                } catch (Exception e) {
                    Notification.show("Fehler beim Löschen des Endgeräts: " + e.getMessage(), 5000,
                            Notification.Position.MIDDLE);
                }
            });

            confirmDialog.open();
        }
    }

    private void navigateBack() {
        getUI().ifPresent(ui -> ui.navigate("app-devices"));
    }
}
