package de.assecutor.votianlt.pages.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.icon.Icon;
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 de.assecutor.votianlt.model.Customer;
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;

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

    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);

        // Header with title and add button
        HorizontalLayout header = new HorizontalLayout();
        header.setWidthFull();
        header.add(new H2("Kunden"));
        Button addCustomerButton = new Button("Kunde hinzufügen", new Icon(VaadinIcon.PLUS));
        header.add(addCustomerButton);
        header.setJustifyContentMode(JustifyContentMode.BETWEEN);
        header.setAlignItems(Alignment.CENTER);
        add(header);

        // Add hint text
        var hintText = new com.vaadin.flow.component.html.Paragraph(
                "Klicken Sie auf einen Eintrag, um ihn zu bearbeiten.");
        hintText.getStyle().set("color", "var(--lumo-secondary-text-color)");
        hintText.getStyle().set("font-size", "var(--lumo-font-size-s)");
        add(hintText);

        // Configure grid columns
        grid.addColumn(Customer::getCompanyName).setHeader("Firma").setAutoWidth(true).setFlexGrow(1).setSortable(true);
        grid.addColumn(customer -> (customer.getFirstname() != null ? customer.getFirstname() : "") + " "
                + (customer.getLastName() != null ? customer.getLastName() : "")).setHeader("Name").setAutoWidth(true)
                .setFlexGrow(1).setSortable(true);
        grid.addColumn(Customer::getMail).setHeader("E-Mail").setAutoWidth(true).setFlexGrow(1).setSortable(true);
        grid.addColumn(Customer::getTelephone).setHeader("Telefon").setAutoWidth(true).setSortable(true);
        grid.addColumn(customer -> (customer.getStreet() != null ? customer.getStreet() : "") + " "
                + (customer.getHouseNumber() != null ? customer.getHouseNumber() : "")).setHeader("Straße")
                .setAutoWidth(true).setFlexGrow(1).setSortable(true);
        grid.addColumn(customer -> (customer.getZip() != null ? customer.getZip() : "") + " "
                + (customer.getCity() != null ? customer.getCity() : "")).setHeader("Ort").setAutoWidth(true)
                .setFlexGrow(1).setSortable(true);

        grid.setMultiSort(true);
        grid.setSizeFull();

        // 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()));
            }
        });

        add(grid);

        // 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)).toList();
        grid.setItems(ownCustomers);
    }
}
