package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.ClientCallable;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dependency.JsModule;
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.notification.Notification;
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.component.html.Input;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.IFrame;
import com.vaadin.flow.server.StreamResource;
import elemental.json.JsonValue;
import elemental.json.JsonType;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.pages.base.ui.view.AdminLayout;
import de.assecutor.votianlt.service.CustomerInvoiceService;
import jakarta.annotation.security.RolesAllowed;

@Route(value = "invoice-generator", layout = AdminLayout.class)
@PageTitle("Rechnungsgenerator")
@RolesAllowed("ADMIN")
@JsModule("./invoice-generator/invoice-generator.js")
public class InvoiceGeneratorView extends VerticalLayout {

    private final CustomerInvoiceService customerInvoiceService;
    private Div canvasContainer;
    private VerticalLayout propertiesPanel;
    private Div selectedElementInfo;

    public InvoiceGeneratorView(CustomerInvoiceService customerInvoiceService) {
        this.customerInvoiceService = customerInvoiceService;

        setId("invoice-generator-view");
        getElement().setAttribute("class", "invoice-generator-view");

        setSpacing(false);
        setPadding(false);
        setMargin(false);
        setWidth("100%");
        setHeight("100%");
        getStyle().set("overflow", "hidden").set("box-sizing", "border-box").set("display", "flex")
                .set("flex-direction", "column");

        // Hauptlayout: Links (Templates) | Mitte (Canvas) | Rechts (Eigenschaften)
        HorizontalLayout mainLayout = new HorizontalLayout();
        mainLayout.setWidth("100%");
        mainLayout.setHeight("calc(100vh - 60px)"); // Abzug für Action-Buttons
        mainLayout.setSpacing(true);
        mainLayout.getStyle().set("overflow", "hidden");

        // Linke Seite: Templates/Bausteine
        VerticalLayout leftPanel = createTemplatesPanel();
        leftPanel.setWidth("250px");
        leftPanel.setHeightFull();
        leftPanel.getStyle().set("flex-shrink", "0").set("min-width", "250px").set("overflow", "auto");

        // Mitte: Canvas mit Konva.js
        VerticalLayout centerPanel = createCanvasPanel();
        centerPanel.setWidth("60%");
        centerPanel.setHeightFull();
        centerPanel.getStyle().set("flex-grow", "1").set("min-width", "0");

        // Rechte Seite: Eigenschaften
        propertiesPanel = createPropertiesPanel();
        propertiesPanel.setWidth("300px");
        propertiesPanel.setHeightFull();
        propertiesPanel.getStyle().set("flex-shrink", "0").set("min-width", "300px").set("overflow", "auto");

        mainLayout.add(leftPanel, centerPanel, propertiesPanel);
        mainLayout.expand(centerPanel);

        add(mainLayout);

        // Aktions-Buttons unter dem Canvas (fixe Höhe)
        HorizontalLayout actionLayout = createActionButtons();
        actionLayout.setHeight("60px");
        actionLayout.getStyle().set("flex-shrink", "0").set("padding", "0 var(--lumo-space-m)");
        add(actionLayout);
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        // Register this view instance and initialize the canvas
        getElement().executeJs("window.invoiceGeneratorView = this;" + "if (window.invoiceGenerator) {"
                + "  console.log('Initializing invoice generator...');" + "  window.invoiceGenerator.init();"
                + "} else {" + "  console.error('Invoice generator not found');" + "}");
    }

    private VerticalLayout createTemplatesPanel() {
        VerticalLayout panel = new VerticalLayout();
        panel.setPadding(true);
        panel.setSpacing(true);
        panel.setHeightFull();
        panel.getStyle().set("background-color", "var(--lumo-contrast-5pct)")
                .set("border-radius", "var(--lumo-border-radius-m)").set("overflow", "auto");

        Span header = new Span("Textbausteine");
        header.getStyle().set("font-weight", "bold").set("font-size", "var(--lumo-font-size-l)");

        // Draggable Templates
        Div textBlock = createDraggableTemplate("Textfeld", VaadinIcon.TEXT_LABEL, "text");
        Div headerBlock = createDraggableTemplate("Überschrift", VaadinIcon.HEADER, "header");
        Div dateBlock = createDraggableTemplate("Datum", VaadinIcon.CALENDAR, "date");
        Div customerBlock = createDraggableTemplate("Kundeninfo", VaadinIcon.USER, "customer");
        Div companyBlock = createDraggableTemplate("Firmeninfo", VaadinIcon.OFFICE, "company");
        Div amountBlock = createDraggableTemplate("Betrag", VaadinIcon.COIN_PILES, "amount");
        Div lineBlock = createDraggableTemplate("Linie", VaadinIcon.LINE_V, "line");
        Div imageBlock = createDraggableTemplate("Bild", VaadinIcon.PICTURE, "image");

        panel.add(header, textBlock, headerBlock, dateBlock, customerBlock, companyBlock, amountBlock, lineBlock,
                imageBlock);

        return panel;
    }

    private Div createDraggableTemplate(String label, VaadinIcon icon, String type) {
        Div template = new Div();
        template.setText(label);
        template.getStyle().set("padding", "var(--lumo-space-m)").set("margin", "var(--lumo-space-xs) 0")
                .set("background-color", "var(--lumo-base-color)").set("border", "1px solid var(--lumo-contrast-20pct)")
                .set("border-radius", "var(--lumo-border-radius-m)").set("cursor", "grab").set("display", "flex")
                .set("align-items", "center").set("gap", "var(--lumo-space-s)").set("user-select", "none");

        // Icon hinzufügen
        Icon templateIcon = icon.create();
        templateIcon.setSize("var(--lumo-icon-size-s)");
        template.getElement().insertChild(0, templateIcon.getElement());

        // Drag & Drop Attribute setzen
        template.getElement().setAttribute("draggable", "true");
        template.getElement().setAttribute("data-template-type", type);
        template.getElement().setAttribute("data-template-label", label);

        // JavaScript Event Listener für Drag Start
        template.getElement()
                .executeJs("this.addEventListener('dragstart', function(e) {"
                        + "  e.dataTransfer.setData('template-type', this.getAttribute('data-template-type'));"
                        + "  e.dataTransfer.setData('template-label', this.getAttribute('data-template-label'));"
                        + "  this.style.opacity = '0.5';" + "});" + "this.addEventListener('dragend', function(e) {"
                        + "  this.style.opacity = '1';" + "});");

        return template;
    }

    private VerticalLayout createCanvasPanel() {
        VerticalLayout panel = new VerticalLayout();
        panel.setPadding(false);
        panel.setSpacing(false);
        panel.setHeightFull();

        // Canvas Container für Konva.js
        canvasContainer = new Div();
        canvasContainer.setId("invoice-canvas-container");
        canvasContainer.setWidth("100%");
        canvasContainer.setHeight("100%");
        canvasContainer.getStyle().set("background-color", "#e8e8e8")
                .set("border", "2px dashed var(--lumo-contrast-30pct)")
                .set("border-radius", "var(--lumo-border-radius-m)").set("position", "relative")
                .set("overflow", "hidden").set("cursor", "default");

        // Drop Zone Event Listener
        canvasContainer.getElement()
                .executeJs("var container = this;" + "container.addEventListener('dragover', function(e) {"
                        + "  e.preventDefault();" + "  e.dataTransfer.dropEffect = 'copy';"
                        + "  container.style.borderColor = 'var(--lumo-primary-color)';" + "});"
                        + "container.addEventListener('dragleave', function(e) {"
                        + "  container.style.borderColor = 'var(--lumo-contrast-30pct)';" + "});"
                        + "container.addEventListener('drop', function(e) {" + "  e.preventDefault();"
                        + "  container.style.borderColor = 'var(--lumo-contrast-30pct)';"
                        + "  var templateType = e.dataTransfer.getData('template-type');"
                        + "  var templateLabel = e.dataTransfer.getData('template-label');"
                        + "  if (templateType && window.invoiceGenerator) {"
                        + "    var rect = container.getBoundingClientRect();" + "    var x = e.clientX - rect.left;"
                        + "    var y = e.clientY - rect.top;"
                        + "    window.invoiceGenerator.addElement(templateType, templateLabel, x, y);" + "  }" + "});");

        panel.add(canvasContainer);
        panel.expand(canvasContainer);

        return panel;
    }

    private VerticalLayout createPropertiesPanel() {
        VerticalLayout panel = new VerticalLayout();
        panel.setPadding(true);
        panel.setSpacing(true);
        panel.setHeightFull();
        panel.getStyle().set("background-color", "var(--lumo-contrast-5pct)")
                .set("border-radius", "var(--lumo-border-radius-m)").set("overflow", "auto");

        Span header = new Span("Eigenschaften");
        header.getStyle().set("font-weight", "bold").set("font-size", "var(--lumo-font-size-l)");

        // Info-Text wenn kein Element ausgewählt
        selectedElementInfo = new Div();
        selectedElementInfo.setText("Klicken Sie auf ein Element im Canvas, um dessen Eigenschaften zu bearbeiten.");
        selectedElementInfo.getStyle().set("color", "var(--lumo-secondary-text-color)").set("font-size",
                "var(--lumo-font-size-s)");

        panel.add(header, selectedElementInfo);

        return panel;
    }

    private HorizontalLayout createActionButtons() {
        HorizontalLayout layout = new HorizontalLayout();
        layout.setWidth("100%");
        layout.setJustifyContentMode(JustifyContentMode.END);
        layout.setPadding(false);
        layout.setSpacing(true);
        layout.setAlignItems(Alignment.CENTER);

        Button clearButton = new Button("Canvas leeren", new Icon(VaadinIcon.TRASH));
        clearButton.addThemeVariants(ButtonVariant.LUMO_ERROR, ButtonVariant.LUMO_TERTIARY);
        clearButton.addClickListener(e -> {
            getElement().executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.clearCanvas(); }");
            showNotification("Canvas wurde geleert");
        });

        Button previewButton = new Button("Vorschau", new Icon(VaadinIcon.EYE));
        previewButton.addThemeVariants(ButtonVariant.LUMO_CONTRAST);
        previewButton.addClickListener(e -> generatePreviewPdf());

        Button saveTemplateButton = new Button("Template speichern", new Icon(VaadinIcon.DOWNLOAD));
        saveTemplateButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        saveTemplateButton.addClickListener(e -> {
            getElement().executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.exportTemplate(); }");
        });

        Button generatePdfButton = new Button("PDF generieren", new Icon(VaadinIcon.FILE_TEXT_O));
        generatePdfButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SUCCESS);
        generatePdfButton.addClickListener(e -> generatePdf());

        layout.add(clearButton, previewButton, saveTemplateButton, generatePdfButton);

        return layout;
    }

    private void generatePdf() {
        try {
            // Hole die Canvas-Daten und generiere PDF
            getElement().executeJs(
                    "if (window.invoiceGenerator) { return window.invoiceGenerator.getCanvasData(); } else { return null; }")
                    .then(json -> {
                        if (json == null) {
                            showNotification("Fehler: Canvas-Daten konnten nicht gelesen werden");
                            return;
                        }
                        // Hier würde die PDF-Generierung erfolgen
                        showNotification("PDF wird generiert... (Demo)");
                    });
        } catch (Exception ex) {
            showNotification("Fehler beim Generieren des PDFs: " + ex.getMessage());
        }
    }

    private void generatePreviewPdf() {
        try {
            getElement().executeJs(
                    "if (window.invoiceGenerator) { return window.invoiceGenerator.exportTemplateJson(); } else { return null; }")
                    .then(result -> {
                        if (result == null) {
                            showNotification("Fehler: Canvas-Daten konnten nicht gelesen werden");
                            return;
                        }
                        try {
                            String templateData;
                            if (result instanceof JsonValue) {
                                JsonValue jsonValue = (JsonValue) result;
                                if (jsonValue.getType() == JsonType.STRING) {
                                    templateData = jsonValue.asString();
                                } else {
                                    templateData = jsonValue.toJson();
                                }
                            } else {
                                templateData = result.toString();
                            }
                            byte[] pdfBytes = customerInvoiceService.generatePdfFromCanvasTemplate(templateData);
                            showPdfInDialog(pdfBytes);
                        } catch (Exception ex) {
                            showNotification("Fehler beim Generieren der Vorschau: " + ex.getMessage());
                        }
                    });
        } catch (Exception ex) {
            showNotification("Fehler: " + ex.getMessage());
        }
    }

    private void showPdfInDialog(byte[] pdfBytes) {
        // Create a stream resource for the PDF
        StreamResource resource = new StreamResource("preview.pdf", () -> new java.io.ByteArrayInputStream(pdfBytes));
        resource.setContentType("application/pdf");
        resource.setCacheTime(0);

        // Create dialog
        Dialog pdfDialog = new Dialog();
        pdfDialog.setHeaderTitle("PDF Vorschau");
        pdfDialog.setWidth("90vw");
        pdfDialog.setHeight("90vh");

        // Create a Div to hold the PDF viewer
        Div pdfContainer = new Div();
        pdfContainer.setWidth("100%");
        pdfContainer.setHeight("100%");
        pdfContainer.getStyle().set("display", "flex").set("flex-direction", "column").set("overflow", "hidden");

        // Use an iframe with data URL for PDF display
        String base64Pdf = java.util.Base64.getEncoder().encodeToString(pdfBytes);
        String dataUrl = "data:application/pdf;base64," + base64Pdf;

        IFrame pdfFrame = new IFrame();
        pdfFrame.setWidth("100%");
        pdfFrame.setHeight("100%");
        pdfFrame.getElement().setAttribute("src", dataUrl);
        pdfFrame.getStyle().set("border", "none").set("flex-grow", "1");

        pdfContainer.add(pdfFrame);

        // Close button
        Button closeButton = new Button("Schließen", e -> pdfDialog.close());
        closeButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        // Download button
        Button downloadButton = new Button("Herunterladen", e -> {
            getElement()
                    .executeJs("const link = document.createElement('a');" + "link.href = 'data:application/pdf;base64,"
                            + base64Pdf + "';" + "link.download = 'vorschau.pdf';" + "link.click();");
        });
        downloadButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);

        pdfDialog.add(pdfContainer);
        pdfDialog.getFooter().add(downloadButton, closeButton);
        pdfDialog.open();
    }

    private void showNotification(String message) {
        Notification.show(message, 3000, Notification.Position.BOTTOM_CENTER);
    }

    // Wird von JavaScript aufgerufen wenn ein Element ausgewählt wird
    @ClientCallable
    public void updatePropertiesPanel(String elementId, String elementType, String text, Double x, Double y,
            Integer fontSize, String color) {
        getUI().ifPresent(ui -> ui.access(() -> {
            propertiesPanel.removeAll();

            Span header = new Span("Eigenschaften");
            header.getStyle().set("font-weight", "bold").set("font-size", "var(--lumo-font-size-l)");

            // Element Typ Anzeige
            Span typeLabel = new Span("Typ: " + elementType);
            typeLabel.getStyle().set("font-size", "var(--lumo-font-size-s)");

            propertiesPanel.add(header, typeLabel);

            // Für Bildelemente: Upload-Button anzeigen
            if ("image".equals(elementType)) {
                MemoryBuffer buffer = new MemoryBuffer();
                Upload upload = new Upload(buffer);
                upload.setAcceptedFileTypes("image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp");
                upload.setMaxFileSize(5 * 1024 * 1024); // 5 MB
                upload.setDropLabel(new Span("Bild hierher ziehen oder klicken"));
                upload.setWidthFull();

                upload.addSucceededListener(event -> {
                    try {
                        // Bild als Base64 kodieren
                        byte[] bytes = buffer.getInputStream().readAllBytes();
                        String base64 = java.util.Base64.getEncoder().encodeToString(bytes);
                        String mimeType = event.getMIMEType();
                        String dataUrl = "data:" + mimeType + ";base64," + base64;

                        // An JavaScript übergeben
                        getElement()
                                .executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.updateElementImage('"
                                        + elementId + "', $0); }", dataUrl);
                        showNotification("Bild erfolgreich hochgeladen");
                    } catch (Exception ex) {
                        showNotification("Fehler beim Hochladen: " + ex.getMessage());
                    }
                });

                upload.addFileRejectedListener(event -> {
                    showNotification("Datei abgelehnt: " + event.getErrorMessage());
                });

                propertiesPanel.add(upload);
            }

            // Text Feld (nur für Text-Elemente)
            if (!"line".equals(elementType) && !"image".equals(elementType)) {
                TextField textField = new TextField("Text");
                textField.setValue(text != null ? text : "");
                textField.setWidthFull();
                textField.addValueChangeListener(e -> {
                    getElement().executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.updateElementText('"
                            + elementId + "', $0); }", e.getValue());
                });
                propertiesPanel.add(textField);
            }

            // X Position
            TextField xField = new TextField("X Position");
            xField.setValue(x != null ? String.valueOf(Math.round(x)) : "0");
            xField.setWidthFull();
            xField.addValueChangeListener(e -> {
                try {
                    double newX = Double.parseDouble(e.getValue());
                    getElement()
                            .executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.updateElementPosition('"
                                    + elementId + "', $0, null); }", newX);
                } catch (NumberFormatException ignored) {
                }
            });
            propertiesPanel.add(xField);

            // Y Position
            TextField yField = new TextField("Y Position");
            yField.setValue(y != null ? String.valueOf(Math.round(y)) : "0");
            yField.setWidthFull();
            yField.addValueChangeListener(e -> {
                try {
                    double newY = Double.parseDouble(e.getValue());
                    getElement()
                            .executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.updateElementPosition('"
                                    + elementId + "', null, $0); }", newY);
                } catch (NumberFormatException ignored) {
                }
            });
            propertiesPanel.add(yField);

            // Font Size (nur für Text-Elemente)
            if (!"line".equals(elementType) && !"image".equals(elementType)) {
                TextField fontSizeField = new TextField("Schriftgröße");
                fontSizeField.setValue(fontSize != null ? String.valueOf(fontSize) : "16");
                fontSizeField.setWidthFull();
                fontSizeField.addValueChangeListener(e -> {
                    try {
                        int newSize = Integer.parseInt(e.getValue());
                        getElement().executeJs(
                                "if (window.invoiceGenerator) { window.invoiceGenerator.updateElementFontSize('"
                                        + elementId + "', $0); }",
                                newSize);
                    } catch (NumberFormatException ignored) {
                    }
                });
                propertiesPanel.add(fontSizeField);

                // Schriftfarbe mit Dialog
                Span colorLabel = new Span("Schriftfarbe");
                colorLabel.getStyle().set("font-size", "var(--lumo-font-size-s)");
                propertiesPanel.add(colorLabel);

                // Aktuelle Farbe anzeigen und klickbar machen
                String currentColor = color != null ? color : "#333333";

                HorizontalLayout colorPreviewLayout = new HorizontalLayout();
                colorPreviewLayout.setSpacing(true);
                colorPreviewLayout.setAlignItems(Alignment.CENTER);
                colorPreviewLayout.setWidthFull();
                colorPreviewLayout.getStyle().set("cursor", "pointer");

                // Farbvorschau-Box
                Div colorPreview = new Div();
                colorPreview.getStyle().set("width", "40px").set("height", "30px").set("background-color", currentColor)
                        .set("border", "1px solid var(--lumo-contrast-30pct)")
                        .set("border-radius", "var(--lumo-border-radius-m)");

                Span colorHexLabel = new Span(currentColor);
                colorHexLabel.getStyle().set("font-family", "monospace").set("font-size", "var(--lumo-font-size-s)");

                colorPreviewLayout.add(colorPreview, colorHexLabel);

                // Color Picker Dialog
                Dialog colorDialog = new Dialog();
                colorDialog.setHeaderTitle("Schriftfarbe wählen");

                VerticalLayout dialogLayout = new VerticalLayout();
                dialogLayout.setSpacing(true);
                dialogLayout.setPadding(true);

                // Color Picker im Dialog
                Input dialogColorPicker = new Input();
                dialogColorPicker.setType("color");
                dialogColorPicker.setValue(currentColor);
                dialogColorPicker.getStyle().set("width", "100%").set("height", "50px").set("padding", "0");

                // Hex-Eingabe im Dialog
                TextField dialogHexField = new TextField("Hex-Farbwert");
                dialogHexField.setValue(currentColor);
                dialogHexField.setWidthFull();

                // Sync zwischen Color Picker und Hex-Feld
                dialogColorPicker.addValueChangeListener(e -> {
                    dialogHexField.setValue(e.getValue());
                });

                dialogHexField.addValueChangeListener(e -> {
                    String newColor = e.getValue();
                    if (newColor.matches("^#[0-9A-Fa-f]{6}$")) {
                        dialogColorPicker.setValue(newColor);
                    }
                });

                dialogLayout.add(dialogColorPicker, dialogHexField);
                colorDialog.add(dialogLayout);

                // Dialog Buttons
                Button dialogCancelButton = new Button("Abbrechen", e -> {
                    colorDialog.close();
                    // Reset to original values
                    dialogColorPicker.setValue(currentColor);
                    dialogHexField.setValue(currentColor);
                });
                dialogCancelButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);

                Button dialogApplyButton = new Button("Übernehmen", e -> {
                    String newColor = dialogColorPicker.getValue();
                    // Update preview
                    colorPreview.getStyle().set("background-color", newColor);
                    colorHexLabel.setText(newColor);
                    // Apply to element
                    getElement().executeJs("if (window.invoiceGenerator) { window.invoiceGenerator.updateElementColor('"
                            + elementId + "', $0); }", newColor);
                    colorDialog.close();
                    showNotification("Farbe übernommen");
                });
                dialogApplyButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

                colorDialog.getFooter().add(dialogCancelButton, dialogApplyButton);

                // Öffne Dialog beim Klick auf die Vorschau
                Runnable openColorDialog = () -> {
                    // Aktualisiere Dialog mit aktuellem Wert
                    String actualColor = colorHexLabel.getText();
                    dialogColorPicker.setValue(actualColor);
                    dialogHexField.setValue(actualColor);
                    colorDialog.open();
                };

                colorPreviewLayout.addClickListener(e -> openColorDialog.run());
                colorPreview.addClickListener(e -> openColorDialog.run());
                colorHexLabel.addClickListener(e -> openColorDialog.run());

                propertiesPanel.add(colorPreviewLayout);
            }

            // Löschen Button
            Button deleteButton = new Button("Element löschen", new Icon(VaadinIcon.TRASH));
            deleteButton.addThemeVariants(ButtonVariant.LUMO_ERROR, ButtonVariant.LUMO_TERTIARY);
            deleteButton.setWidthFull();
            deleteButton.addClickListener(e -> {
                getElement().executeJs(
                        "if (window.invoiceGenerator) { window.invoiceGenerator.deleteElement('" + elementId + "'); }");
                resetPropertiesPanel();
            });
            propertiesPanel.add(deleteButton);
        }));
    }

    /**
     * Wird von JavaScript aufgerufen wenn die Auswahl aufgehoben wird
     */
    @ClientCallable
    public void resetPropertiesPanel() {
        getUI().ifPresent(ui -> ui.access(() -> {
            propertiesPanel.removeAll();

            Span header = new Span("Eigenschaften");
            header.getStyle().set("font-weight", "bold").set("font-size", "var(--lumo-font-size-l)");

            selectedElementInfo = new Div();
            selectedElementInfo
                    .setText("Klicken Sie auf ein Element im Canvas, um dessen Eigenschaften zu bearbeiten.");
            selectedElementInfo.getStyle().set("color", "var(--lumo-secondary-text-color)").set("font-size",
                    "var(--lumo-font-size-s)");

            propertiesPanel.add(header, selectedElementInfo);
        }));
    }
}
