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.html.H1;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import de.assecutor.votianlt.pages.service.PasswordResetService;

import java.util.Map;

@Route("forget-password")
@AnonymousAllowed
public class ForgetPasswordView extends VerticalLayout implements BeforeEnterObserver, HasDynamicTitle {

    private final PasswordResetService passwordResetService;

    private String token;
    private PasswordResetService.UserType userType;

    private final PasswordField newPassword;
    private final PasswordField confirmPassword;

    public ForgetPasswordView(PasswordResetService passwordResetService) {
        this.passwordResetService = passwordResetService;

        setSizeFull();
        setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.CENTER);
        addClassName("form-page");

        VerticalLayout container = new VerticalLayout();
        container.setWidth("400px");
        container.setMaxWidth("100%");
        container.setPadding(true);
        container.setSpacing(true);
        container.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH);
        container.addClassNames("form-shell", "narrow", "form-card");

        H1 title = new H1("Neues Passwort festlegen");
        title.addClassName("form-title");

        newPassword = new PasswordField("Neues Passwort");
        confirmPassword = new PasswordField("Passwort bestätigen");

        Button submit = new Button("Passwort speichern", e -> onSubmit());
        submit.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        container.add(title, newPassword, confirmPassword, submit);
        add(container);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        Map<String, java.util.List<String>> params = event.getLocation().getQueryParameters().getParameters();
        String tokenParam = params.getOrDefault("token", java.util.List.of("")).getFirst();
        String typeParam = params.getOrDefault("type", java.util.List.of("")).getFirst();
        this.token = tokenParam != null ? tokenParam.trim() : "";
        this.userType = "app_user".equalsIgnoreCase(typeParam) ? PasswordResetService.UserType.APP_USER
                : PasswordResetService.UserType.USERS;

        if (this.token.isEmpty() || !passwordResetService.isTokenValid(this.token, this.userType)) {
            // Store a flash message in the VaadinSession so it persists through reroute
            com.vaadin.flow.server.VaadinSession.getCurrent().setAttribute("flashMessage",
                    "Ungültiger oder abgelaufener Token.");
            event.rerouteTo(LoginView.class);
        }
    }

    private void onSubmit() {
        String p1 = newPassword.getValue();
        String p2 = confirmPassword.getValue();
        if (p1 == null || p1.isBlank()) {
            Notification.show("Bitte geben Sie ein neues Passwort ein.", 3000, Notification.Position.MIDDLE);
            return;
        }
        if (!p1.equals(p2)) {
            Notification.show("Die Passwörter stimmen nicht überein.", 3000, Notification.Position.MIDDLE);
            return;
        }
        boolean ok = passwordResetService.resetPassword(token, userType, p1);
        if (ok) {
            Notification.show("Passwort wurde erfolgreich geändert.", 3000, Notification.Position.MIDDLE);
            getUI().ifPresent(ui -> ui.navigate("login"));
        } else {
            Notification.show("Token ungültig oder abgelaufen.", 3000, Notification.Position.MIDDLE);
        }
    }

    @Override
    public String getPageTitle() {
        return getTranslation("page.title.password.forget");
    }
}
