package ru.vyatsu.qr_access_admin.client.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import jakarta.annotation.security.PermitAll;
import ru.vyatsu.qr_access_admin.client.component.ClientEditor;
import ru.vyatsu.qr_access_admin.client.entity.ClientEntity;
import ru.vyatsu.qr_access_admin.client.entity.ClientRepository;
import ru.vyatsu.qr_access_admin.common.MainLayout;

import java.util.List;

@Route(value = "clients", layout = MainLayout.class)
@PageTitle("Клиенты")
@PermitAll
public class ClientView extends VerticalLayout {
    private final ClientRepository repository;
    private final Grid<ClientEntity> grid;
    private final ClientEditor editor;

    public ClientView(ClientRepository repository) {
        this.repository = repository;

        var addButton = new Button("Добавить клиента", VaadinIcon.PLUS.create());
        grid = new Grid<>(ClientEntity.class);
        grid.setColumns("id", "email", "emailIsConfirmed");
        editor = new ClientEditor();

        var actionsLayout = new HorizontalLayout(addButton);
        add(actionsLayout, grid, editor);

        this.configureEditor();

        addButton.addClickListener(e -> editClient(new ClientEntity()));

        grid.setHeight("200px");
        grid.asSingleSelect().addValueChangeListener(e -> editClient(e.getValue()));

        refreshClientGrid();
    }

    private void refreshClientGrid() {
        List<ClientEntity> entities = repository.findAll();
        grid.setItems(entities);
    }

    private void editClient(ClientEntity client) {
        if (client == null) {
            editor.setVisible(false);
        } else {
            editor.setVisible(true);
            editor.setCurrentClient(client);
        }
    }

    private void configureEditor() {
        editor.setVisible(false);

        editor.setSaveListener(client -> {
            repository.save(client);
            refreshClientGrid();
            editClient(null);
        });

        editor.setDeleteListener(client -> {
            repository.deleteById(client.getId());
            refreshClientGrid();
            editClient(null);
        });

        editor.setCancelListener(() -> editClient(null));
    }
}
