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.formlayout.FormLayout;
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.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.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.AppUser;
import de.assecutor.votianlt.model.AppDevice;
import de.assecutor.votianlt.pages.service.AppUserService;
import de.assecutor.votianlt.pages.service.AppDeviceService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;

@PageTitle("Neuen App-Nutzer anlegen")
@Route(value = "add-app-user", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class AddAppUserView extends VerticalLayout {

    private final AppUserService appUserService;
    private final AppDeviceService appDeviceService;
    private final Binder<AppUser> binder = new Binder<>(AppUser.class);

    // Form fields
    private final TextField designationField = new TextField("Bezeichnung (HH H 000)");
    private final TextField firstnameField = new TextField("Vorname");
    private final TextField lastnameField = new TextField("Nachname");
    private final TextField phoneField = new TextField("Telefon (Mobil)");
    private final TextField appCodeField = new TextField("App-Code");
    private final TextField emailField = new TextField("E-Mail-Adresse");
    private final PasswordField passwordField = new PasswordField("Passwort");
    private final PasswordField confirmPasswordField = new PasswordField("Passwort wiederholen");
    private final ComboBox<AppDevice> deviceComboBox = new ComboBox<>("Endgerät");

    @Autowired
    public AddAppUserView(AppUserService appUserService, AppDeviceService appDeviceService) {
        this.appUserService = appUserService;
        this.appDeviceService = appDeviceService;
        setSizeFull();
        setPadding(true);
        setSpacing(true);

        // Center content vertically
        setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);

        // Create main content container
        VerticalLayout contentContainer = new VerticalLayout();
        contentContainer.setWidth("600px");
        contentContainer.setMaxWidth("90%");
        contentContainer.setSpacing(true);
        contentContainer.setPadding(true);
        contentContainer.getStyle().set("background", "var(--lumo-contrast-5pct)");
        contentContainer.getStyle().set("border-radius", "var(--lumo-border-radius)");
        contentContainer.getStyle().set("box-shadow", "var(--lumo-box-shadow-s)");

        // Header with title and back button
        HorizontalLayout header = new HorizontalLayout();
        header.setAlignItems(FlexComponent.Alignment.CENTER);
        header.setSpacing(true);

        H2 title = new H2("Neuen App-Nutzer anlegen");
        title.getStyle().set("margin", "0");

        Button backButton = new Button("Zurück", new Icon(VaadinIcon.ARROW_LEFT));
        backButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        backButton.addClickListener(e -> navigateBack());

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

        // Form layout
        FormLayout formLayout = new FormLayout();
        formLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1));

        // Configure fields
        designationField.setPlaceholder("(HH H 000)");
        designationField.setWidthFull();

        firstnameField.setWidthFull();
        lastnameField.setWidthFull();

        // Create horizontal layout for firstname and lastname
        HorizontalLayout nameLayout = new HorizontalLayout();
        nameLayout.setWidthFull();
        nameLayout.setSpacing(true);
        nameLayout.add(firstnameField, lastnameField);

        phoneField.setWidthFull();
        appCodeField.setWidthFull();
        emailField.setWidthFull();
        passwordField.setWidthFull();
        passwordField.setRequired(true);
        confirmPasswordField.setWidthFull();
        confirmPasswordField.setRequired(true);

        // Configure device dropdown
        // Geräteauswahl vorbereiten
        deviceComboBox.setWidthFull();
        deviceComboBox.setItemLabelGenerator(device -> device.getName());
        deviceComboBox.setRequired(true);
        deviceComboBox.setPlaceholder("Bitte wählen...");
        deviceComboBox.setItems(appDeviceService.findUnassignedDevices());

        // Add fields to form
        formLayout.add(designationField);
        formLayout.add(nameLayout);
        formLayout.add(phoneField);
        formLayout.add(appCodeField);
        formLayout.add(emailField);
        formLayout.add(passwordField);
        formLayout.add(confirmPasswordField);
        formLayout.add(deviceComboBox);

        contentContainer.add(formLayout);

        // Submit button
        Button submitButton = new Button("App-Nutzer anlegen", e -> createAppUser());
        submitButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        submitButton.setWidthFull();
        contentContainer.add(submitButton);

        // Add content container to main layout
        add(contentContainer);

        // Setup binder
        setupBinder();

        // Fill with test data
        populateTestData();
    }

    private void setupBinder() {
        // Bind fields to AppUser properties
        binder.forField(designationField).bind(AppUser::getBezeichnung, AppUser::setBezeichnung);
        binder.forField(firstnameField).bind(AppUser::getVorname, AppUser::setVorname);
        binder.forField(lastnameField).bind(AppUser::getNachname, AppUser::setNachname);
        binder.forField(phoneField).bind(AppUser::getTelefon, AppUser::setTelefon);
        binder.forField(appCodeField).bind(AppUser::getAppCode, AppUser::setAppCode);
        binder.forField(emailField).bind(AppUser::getEmail, AppUser::setEmail);
        binder.forField(passwordField).asRequired("Passwort ist erforderlich").bind(AppUser::getPassword,
                AppUser::setPassword);

        // Confirm password field validation
        binder.forField(confirmPasswordField).asRequired("Passwort wiederholen ist erforderlich")
                .withValidator(confirmPassword -> confirmPassword.equals(passwordField.getValue()),
                        "Passwörter stimmen nicht überein")
                .bind(appUser -> "", // Dummy getter - this field is not stored
                        (appUser, value) -> {
                        } // Dummy setter - this field is not stored
                );
        binder.forField(deviceComboBox).asRequired("Bitte ein Gerät auswählen").bind(appUser -> null, // Initialwert,
                                                                                                      // wird beim
                                                                                                      // Erstellen
                                                                                                      // gesetzt
                (appUser, appDevice) -> appUser.setAppDeviceId(appDevice != null ? appDevice.getId() : null));
    }

    private void createAppUser() {
        try {
            // Create new AppUser object
            AppUser newAppUser = new AppUser();
            binder.writeBean(newAppUser);

            // Save AppUser first to get the ObjectId
            AppUser savedUser = appUserService.createAppUser(newAppUser);

            // Referenz im AppDevice setzen
            AppDevice selectedDevice = deviceComboBox.getValue();
            if (selectedDevice != null && savedUser != null && savedUser.getId() != null) {
                selectedDevice.setAppUserId(savedUser.getId());
                appDeviceService.updateAppDevice(selectedDevice);
            }

            // Show success message
            Notification.show("App-Nutzer erfolgreich angelegt", 3000, Notification.Position.MIDDLE);

            // Navigate back to app user list
            navigateBack();

        } catch (ValidationException e) {
            Notification.show("Bitte überprüfen Sie die Eingaben", 3000, Notification.Position.MIDDLE);
        }
    }

    private void populateTestData() {
        // Fill designation field
        designationField.setValue("HH H 001");

        // Fill name fields
        firstnameField.setValue("Max");
        lastnameField.setValue("Mustermann");

        // Fill phone field
        phoneField.setValue("+49 123 456789");

        // Fill app code field
        appCodeField.setValue("APP001");

        // Fill email field
        emailField.setValue("max.mustermann@example.com");

        // Fill password field
        passwordField.setValue("testpassword123");

        // Fill confirm password field
        confirmPasswordField.setValue("testpassword123");

        // Set device to iPhone
        // deviceComboBox.setValue("iPhone"); // This line is removed as deviceComboBox
        // is now a ComboBox<AppDevice>
    }

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