package de.votian.web.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.H3;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
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.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.votian.web.service.RestClientService;

import java.util.LinkedHashMap;
import java.util.Map;

@Route(value = "password", layout = MainLayout.class)
@PageTitle("Votian - Passwort")
public class PasswordChangeView extends VerticalLayout {

    public PasswordChangeView(RestClientService restClient) {
        setPadding(true);
        setSpacing(true);

        PasswordField oldPasswordField = new PasswordField("Aktuelles Passwort");
        PasswordField newPasswordField = new PasswordField("Neues Passwort");
        PasswordField confirmPasswordField = new PasswordField("Neues Passwort wiederholen");

        FormLayout form = new FormLayout();
        form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1));
        form.add(oldPasswordField, newPasswordField, confirmPasswordField);

        Button saveButton = new Button("Passwort aendern", event -> {
            if (!newPasswordField.getValue().equals(confirmPasswordField.getValue())) {
                Notification.show("Die neuen Passwoerter stimmen nicht ueberein.", 4000, Notification.Position.MIDDLE)
                        .addThemeVariants(NotificationVariant.LUMO_ERROR);
                return;
            }

            try {
                Map<String, Object> request = new LinkedHashMap<>();
                request.put("oldPassword", oldPasswordField.getValue());
                request.put("newPassword", newPasswordField.getValue());
                restClient.post("/auth/change-password", request, LinkedHashMap.class);

                oldPasswordField.clear();
                newPasswordField.clear();
                confirmPasswordField.clear();
                Notification.show("Passwort geaendert.", 3000, Notification.Position.MIDDLE)
                        .addThemeVariants(NotificationVariant.LUMO_SUCCESS);
            } catch (Exception e) {
                Notification.show("Passwort konnte nicht geaendert werden.", 5000, Notification.Position.MIDDLE)
                        .addThemeVariants(NotificationVariant.LUMO_ERROR);
            }
        });
        saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        add(new H3("Passwort aendern"), form, new HorizontalLayout(saveButton));
    }
}
