package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Main;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.theme.lumo.LumoUtility;
import de.assecutor.votianlt.model.Customer;
import de.assecutor.votianlt.pages.base.ui.component.ViewToolbar;
import de.assecutor.votianlt.pages.service.CustomerService;

import java.time.Clock;

import static com.vaadin.flow.spring.data.VaadinSpringDataHelpers.toSpringPageRequest;

@Route(value = "customer", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@Menu(order = 0, icon = "vaadin:clipboard-check", title = "Kunden")
public class CustomersView extends Main implements HasDynamicTitle {
    final TextField description;
    final Button createBtn;
    final Grid<Customer> todoGrid;

    public CustomersView(CustomerService todoService, Clock clock) {
        description = new TextField();
        description.setPlaceholder(getTranslation("jobs.filter.search"));
        description.setMaxLength(255);
        description.setMinWidth("20em");

        createBtn = new Button(getTranslation("addcustomer.button.submit"), event -> addCustomer());
        createBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        todoGrid = new Grid<>();
        todoGrid.setItems(query -> todoService.list(toSpringPageRequest(query)).stream()
                .filter(c -> !c.isInternal()));
        todoGrid.addColumn(Customer::getCompanyName).setHeader(getTranslation("customers.column.company"));
        todoGrid.setSizeFull();
        todoGrid.addClassName("data-grid");

        setSizeFull();
        addClassNames(LumoUtility.BoxSizing.BORDER, LumoUtility.Display.FLEX, LumoUtility.FlexDirection.COLUMN,
                LumoUtility.Padding.MEDIUM, LumoUtility.Gap.SMALL);
        addClassName("data-view");

        ViewToolbar toolbar = new ViewToolbar(getTranslation("customers.title"), createBtn);
        createBtn.addClassName("toolbar-primary-action");

        Div gridPanel = new Div(todoGrid);
        gridPanel.addClassNames("surface-panel", "data-grid-panel");
        gridPanel.setSizeFull();

        add(toolbar, gridPanel);
    }

    private void addCustomer() {
        UI.getCurrent().navigate("add_customer");
    }

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