package de.nilzbu.mytimetracker.ui.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.MultiSelectComboBox;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.H2;
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.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.nilzbu.mytimetracker.model.User;
import de.nilzbu.mytimetracker.repository.UserRepository;
import de.nilzbu.mytimetracker.ui.layout.MainLayout;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@Route(value = "admin/users", layout = MainLayout.class)
@PageTitle("Benutzerverwaltung")
@RolesAllowed("ROLE_ADMIN")
public class UserAdminView extends VerticalLayout {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    private final Grid<User> userGrid = new Grid<>(User.class, false);
    private final TextField usernameField = new TextField("Benutzername");
    private final PasswordField passwordField = new PasswordField("Passwort");
    private final MultiSelectComboBox<String> rolesField = new MultiSelectComboBox<>("Rollen");

    private final Button saveButton = new Button("Speichern");
    private final Button deleteButton = new Button("Löschen");

    private User selectedUser;

    public UserAdminView(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;

        add(new H2("Benutzerverwaltung"));
        configureGrid();
        configureForm();
        refreshGrid();
    }

    private void configureGrid() {
        userGrid.addColumn(User::getUsername).setHeader("Benutzername");
        userGrid.addColumn(user -> String.join(", ", user.getRoles())).setHeader("Rollen");
        userGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
        userGrid.setWidthFull();

        userGrid.asSingleSelect().addValueChangeListener(e -> {
            selectedUser = e.getValue();
            if (selectedUser != null) {
                usernameField.setValue(selectedUser.getUsername());
                rolesField.setValue(selectedUser.getRoles());
                passwordField.clear();
            }
        });

        add(userGrid);
    }

    private void configureForm() {
        rolesField.setItems("ROLE_USER", "ROLE_ADMIN");

        saveButton.addClickListener(e -> {
            if (selectedUser != null) {
                selectedUser.setUsername(usernameField.getValue());
                selectedUser.setRoles(rolesField.getValue());
                if (!passwordField.isEmpty()) {
                    selectedUser.setPassword(passwordEncoder.encode(passwordField.getValue()));
                }
                userRepository.save(selectedUser);
            } else {
                User newUser = User.builder()
                        .username(usernameField.getValue())
                        .roles(rolesField.getValue())
                        .enabled(true)
                        .locked(false)
                        .password(passwordEncoder.encode(passwordField.getValue()))
                        .build();
                userRepository.save(newUser);
            }
            clearForm();
            refreshGrid();
        });

        deleteButton.addClickListener(e -> {
            if (selectedUser != null) {
                userRepository.delete(selectedUser);
                clearForm();
                refreshGrid();
            }
        });

        HorizontalLayout formLayout = new HorizontalLayout(usernameField, passwordField, rolesField, saveButton, deleteButton);
        formLayout.setWidthFull();
        add(formLayout);
    }

    private void refreshGrid() {
        List<User> users = userRepository.findAll();
        userGrid.setItems(users);
    }

    private void clearForm() {
        selectedUser = null;
        usernameField.clear();
        passwordField.clear();
        rolesField.clear();
    }
}