package de.votian.web.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
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.votian.web.model.SessionData;
import de.votian.web.service.RestClientService;

import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.Map;

@Route(value = "statistics", layout = MainLayout.class)
@PageTitle("Votian - Statistik")
public class StatisticsView extends VerticalLayout {

    private final RestClientService restClient;
    private final SessionData sessionData;

    private final Span totalJobs = new Span("-");
    private final Span openJobs = new Span("-");
    private final Span deliveredJobs = new Span("-");
    private final Span cancelledJobs = new Span("-");
    private final Span revenue = new Span("-");
    private final Span courierCosts = new Span("-");

    public StatisticsView(RestClientService restClient, SessionData sessionData) {
        this.restClient = restClient;
        this.sessionData = sessionData;

        setPadding(true);
        setSpacing(true);

        DatePicker fromDate = new DatePicker("Von");
        fromDate.setValue(LocalDate.now().withDayOfMonth(1));
        DatePicker toDate = new DatePicker("Bis");
        toDate.setValue(LocalDate.now());

        Button loadButton = new Button("Auswerten", event -> load(fromDate.getValue(), toDate.getValue()));
        loadButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        HorizontalLayout filterBar = new HorizontalLayout(fromDate, toDate, loadButton);
        HorizontalLayout cards = new HorizontalLayout(
                createCard("Auftraege gesamt", totalJobs),
                createCard("Offen", openJobs),
                createCard("Zugestellt", deliveredJobs),
                createCard("Storniert", cancelledJobs),
                createCard("Umsatz", revenue),
                createCard("Kurierkosten", courierCosts)
        );
        cards.setWidthFull();

        add(new H3("Statistik"), filterBar, cards);
        load(fromDate.getValue(), toDate.getValue());
    }

    private void load(LocalDate fromDate, LocalDate toDate) {
        if (sessionData.getHeadquartersId() == null) {
            return;
        }
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> data = restClient.get(
                    "/reporting/statistics?hqId=" + sessionData.getHeadquartersId()
                            + "&from=" + fromDate + "&to=" + toDate,
                    LinkedHashMap.class
            );
            totalJobs.setText(str(data.get("totalJobs")));
            openJobs.setText(str(data.get("openJobs")));
            deliveredJobs.setText(str(data.get("deliveredJobs")));
            cancelledJobs.setText(str(data.get("cancelledJobs")));
            revenue.setText(str(data.get("totalRevenue")));
            courierCosts.setText(str(data.get("totalCourierCosts")));
        } catch (Exception e) {
            Notification.show("Statistik konnte nicht geladen werden.", 4000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
        }
    }

    private VerticalLayout createCard(String title, Span value) {
        VerticalLayout card = new VerticalLayout();
        card.setPadding(true);
        card.setSpacing(false);
        card.getStyle()
                .set("border", "1px solid var(--lumo-contrast-20pct)")
                .set("border-radius", "var(--lumo-border-radius-l)")
                .set("min-width", "180px");

        H3 headline = new H3(title);
        headline.getStyle().set("margin", "0");
        value.getStyle().set("font-size", "var(--lumo-font-size-xl)").set("font-weight", "700");
        card.add(headline, value);
        return card;
    }

    private String str(Object value) {
        return value != null ? value.toString() : "-";
    }
}
