package de.votian.web.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.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.votian.web.model.SessionData;
import de.votian.web.service.RestClientService;

import java.util.*;

@Route(value = "couriers", layout = MainLayout.class)
@PageTitle("Votian - Kuriere")
public class CourierListView extends VerticalLayout {

    private final RestClientService restClient;
    private final SessionData sessionData;
    private final Grid<Map<String, Object>> grid;

    public CourierListView(RestClientService restClient, SessionData sessionData) {
        this.restClient = restClient;
        this.sessionData = sessionData;
        setSizeFull();
        setPadding(true);

        TextField searchField = new TextField();
        searchField.setPlaceholder("Kurier suchen...");
        searchField.setPrefixComponent(VaadinIcon.SEARCH.create());
        searchField.setValueChangeMode(ValueChangeMode.LAZY);
        searchField.addValueChangeListener(e -> search(e.getValue()));

        Button newButton = new Button("Neuer Kurier", VaadinIcon.PLUS.create(), e ->
                getUI().ifPresent(ui -> ui.navigate(CourierDetailView.class)));
        newButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        newButton.setVisible(sessionData.canManageCouriers());

        HorizontalLayout toolbar = new HorizontalLayout(searchField, newButton);
        toolbar.setWidthFull();
        toolbar.expand(searchField);

        grid = new Grid<>();
        grid.addColumn(m -> m.get("eid")).setHeader("Kurier-Nr.").setSortable(true).setAutoWidth(true);
        grid.addColumn(m -> m.get("sid")).setHeader("SID").setAutoWidth(true);
        grid.addColumn(m -> m.get("companyName")).setHeader("Firma").setFlexGrow(2);
        grid.addColumn(m -> m.get("contact")).setHeader("Ansprechpartner").setFlexGrow(1);
        grid.addColumn(m -> m.get("available")).setHeader("Verfuegbar").setAutoWidth(true);
        grid.setSizeFull();

        grid.addItemClickListener(e -> {
            Object id = e.getItem().get("id");
            if (id != null) {
                getUI().ifPresent(ui -> ui.navigate("couriers/" + id));
            }
        });

        add(toolbar, grid);
        loadCouriers();
    }

    private void loadCouriers() {
        if (sessionData.getHeadquartersId() == null) return;
        try {
            Object[] couriers = restClient.get("/couriers/hq/" + sessionData.getHeadquartersId(), Object[].class);
            if (couriers != null) {
                List<Map<String, Object>> items = new ArrayList<>();
                for (Object c : couriers) {
                    if (c instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> map = (Map<String, Object>) c;
                        items.add(map);
                    }
                }
                grid.setItems(items);
            }
        } catch (Exception e) {
            Notification.show("Fehler: " + e.getMessage());
        }
    }

    private void search(String term) {
        if (term == null || term.trim().isEmpty()) {
            loadCouriers();
            return;
        }
        if (sessionData.getHeadquartersId() == null) return;
        try {
            Object[] results = restClient.get(
                    "/couriers/search?hqId=" + sessionData.getHeadquartersId() + "&term=" + term, Object[].class);
            if (results != null) {
                List<Map<String, Object>> items = new ArrayList<>();
                for (Object c : results) {
                    if (c instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> map = (Map<String, Object>) c;
                        items.add(map);
                    }
                }
                grid.setItems(items);
            }
        } catch (Exception e) {
            Notification.show("Suchfehler: " + e.getMessage());
        }
    }
}
