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.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Paragraph;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.Customer;
import de.assecutor.votianlt.pages.base.ui.component.ViewToolbar;
import de.assecutor.votianlt.pages.service.CustomerService;
import de.assecutor.votianlt.security.SecurityService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;

@Route(value = "customers", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class ShowCustomersView extends VerticalLayout implements HasDynamicTitle {

    private final CustomerService customerService;
    private final SecurityService securityService;
    private final Grid<Customer> grid = new Grid<>(Customer.class, false);

    @Autowired
    public ShowCustomersView(CustomerService customerService, SecurityService securityService) {
        this.customerService = customerService;
        this.securityService = securityService;
        setSizeFull();
        setPadding(true);
        setSpacing(true);
        addClassName("data-view");

        Button addCustomerButton = new Button(getTranslation("customers.button.add"), new Icon(VaadinIcon.PLUS));
        addCustomerButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        add(new ViewToolbar(getTranslation("customers.title"), addCustomerButton));

        // Add hint text
        Paragraph hintText = new Paragraph(getTranslation("customers.hint.click"));
        hintText.addClassName("list-hint");
        add(hintText);

        // Configure grid columns
        grid.addColumn(Customer::getCompanyName).setHeader(getTranslation("customers.column.company"))
                .setAutoWidth(true).setFlexGrow(1).setSortable(true);
        grid.addColumn(customer -> (customer.getFirstname() != null ? customer.getFirstname() : "") + " "
                + (customer.getLastName() != null ? customer.getLastName() : ""))
                .setHeader(getTranslation("customers.column.name")).setAutoWidth(true).setFlexGrow(1).setSortable(true);
        grid.addColumn(Customer::getMail).setHeader(getTranslation("customers.column.email")).setAutoWidth(true)
                .setFlexGrow(1).setSortable(true);
        grid.addColumn(Customer::getTelephone).setHeader(getTranslation("customers.column.phone")).setAutoWidth(true)
                .setSortable(true);

        grid.setMultiSort(true);
        grid.setSizeFull();
        grid.addClassName("data-grid");

        // Make grid rows clickable
        grid.setSelectionMode(Grid.SelectionMode.SINGLE);
        grid.getStyle().set("cursor", "pointer");

        // Add click listener to navigate to edit view
        grid.addItemClickListener(event -> {
            Customer customer = event.getItem();
            if (customer != null && customer.getId() != null) {
                getUI().ifPresent(ui -> ui.navigate("edit-customer/" + customer.getId().toHexString()));
            }
        });

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

        add(gridPanel);

        // Button action
        addCustomerButton.addClickListener(e -> getUI().ifPresent(ui -> ui.navigate("add-customer")));

        loadData();
    }

    private void loadData() {
        var customers = customerService.findAll();
        var currentUserId = securityService.getCurrentUserId();
        var ownCustomers = customers.stream()
                .filter(c -> c.getCreatedBy() != null && c.getCreatedBy().equals(currentUserId))
                .filter(c -> !c.isInternal()).toList();
        grid.setItems(ownCustomers);
    }

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