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/user-management", layout = MainLayout.class)
@PageTitle("User Management")
@RolesAllowed("ROLE_ADMIN")
public class UserManagementView 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("Username");
    private final PasswordField passwordField = new PasswordField("Password");
    private final MultiSelectComboBox<String> rolesField = new MultiSelectComboBox<>("Roles");

    private final Button saveButton = new Button("Save");
    private final Button deleteButton = new Button("Delete");

    private User selectedUser;

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

        add(new H2("User Management"));
        setupUserGrid();
        setupFormLayout();
        loadUsersToGrid();
    }

    private void setupUserGrid() {
        userGrid.addColumn(User::getUsername).setHeader("Username");
        userGrid.addColumn(user -> String.join(", ", user.getRoles())).setHeader("Roles");
        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 setupFormLayout() {
        rolesField.setItems("ROLE_USER", "ROLE_ADMIN");

        saveButton.addClickListener(e -> saveOrUpdateUser());
        deleteButton.addClickListener(e -> deleteUser());

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

    private void saveOrUpdateUser() {
        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);
        }

        resetFormFields();
        loadUsersToGrid();
    }

    private void deleteUser() {
        if (selectedUser != null) {
            userRepository.delete(selectedUser);
            resetFormFields();
            loadUsersToGrid();
        }
    }

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

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