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.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.PageTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.AppDevice;
import de.assecutor.votianlt.pages.service.AppDeviceService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;

@PageTitle("Neues Endgerät anlegen")
@Route(value = "add-app-device", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class AddAppDeviceView extends VerticalLayout {

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

    // Formularfelder
    private final TextField nameField;

    @Autowired
    public AddAppDeviceView(AppDeviceService appDeviceService) {
        this.appDeviceService = appDeviceService;

        // 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%");

        // 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("Neues Endgerät anlegen");
        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);
        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 -> createAppDevice());

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

        add(contentContainer);

        // Testdaten einfügen
        populateTestData();

        // Binder konfigurieren
        setupBinder();
    }

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

    private void populateTestData() {
        nameField.setValue("iPhone 15 Pro");
    }

    private void createAppDevice() {
        if (binder.validate().isOk()) {
            try {
                AppDevice appDevice = new AppDevice();
                binder.writeBean(appDevice);

                // Explizit als nicht zugeordnet speichern
                appDevice.setAppUserId(null);

                AppDevice savedDevice = appDeviceService.createAppDevice(appDevice);

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

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

            } catch (Exception e) {
                Notification.show("Fehler beim Anlegen 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 navigateBack() {
        getUI().ifPresent(ui -> ui.navigate("app-devices"));
    }
}
