package dev.lions.user.manager.client.view;

import dev.lions.user.manager.client.api.AuditRestClient;
import dev.lions.user.manager.client.api.HealthRestClient;
import dev.lions.user.manager.client.api.UserRestClient;
import dev.lions.user.manager.enums.audit.TypeActionAudit;
import jakarta.annotation.PostConstruct;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.primefaces.model.charts.ChartData;
import org.primefaces.model.charts.axes.cartesian.CartesianScales;
import org.primefaces.model.charts.axes.cartesian.linear.CartesianLinearAxes;
import org.primefaces.model.charts.bar.BarChartDataSet;
import org.primefaces.model.charts.bar.BarChartModel;
import org.primefaces.model.charts.bar.BarChartOptions;
import org.primefaces.model.charts.optionconfig.title.Title;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Named
@ViewScoped
@Slf4j
@SuppressWarnings("deprecation") // ChartData API dépréciée - migration vers JSON prévue
public class DashboardView implements Serializable {

    @Inject
    @RestClient
    AuditRestClient auditRestClient;

    @Inject
    @RestClient
    HealthRestClient healthRestClient;

    @Inject
    @RestClient
    UserRestClient userRestClient;

    @ConfigProperty(name = "lions.user.manager.default.realm", defaultValue = "test-realm")
    String defaultRealm;

    @Getter
    private long totalSuccesses;

    @Getter
    private long totalFailures;

    @Getter
    private long activeUsers;

    @Getter
    private boolean systemHealthy;

    @Getter
    private BarChartModel barModel;

    @PostConstruct
    public void init() {
        loadStats();
        createBarModel();
    }

    public void loadStats() {
        try {
            totalSuccesses = auditRestClient.getSuccessCount(null, null);
            totalFailures = auditRestClient.getFailureCount(null, null);

            // Assuming we display active users for default realm
            // Ideally we would have an endpoint for global stats
            activeUsers = 0; // Placeholder until we have count endpoint in UserRestClient or general stats

            try {
                Map<String, Object> health = healthRestClient.getServiceStatus();
                systemHealthy = "UP".equals(health.get("status"));
            } catch (Exception e) {
                systemHealthy = false;
            }

        } catch (Exception e) {
            log.error("Error loading stats", e);
        }
    }

    @SuppressWarnings("deprecation") // ChartData sera remplacé par une approche JSON moderne dans une version future
    public void createBarModel() {
        barModel = new BarChartModel();
        ChartData data = new ChartData();

        BarChartDataSet barDataSet = new BarChartDataSet();
        barDataSet.setLabel("Activités par type");

        List<Object> values = new ArrayList<>();
        List<String> labels = new ArrayList<>();
        List<String> bgColor = new ArrayList<>();
        List<String> borderColor = new ArrayList<>();

        try {
            Map<TypeActionAudit, Long> stats = auditRestClient.getActionStatistics(null, null);

            for (Map.Entry<TypeActionAudit, Long> entry : stats.entrySet()) {
                labels.add(entry.getKey().name());
                values.add(entry.getValue());
                bgColor.add("rgba(75, 192, 192, 0.2)");
                borderColor.add("rgb(75, 192, 192)");
            }
        } catch (Exception e) {
            log.error("Error loading chart data", e);
        }

        barDataSet.setData(values);
        barDataSet.setBackgroundColor(bgColor);
        barDataSet.setBorderColor(borderColor);
        barDataSet.setBorderWidth(1);

        data.addChartDataSet(barDataSet);
        data.setLabels(labels);

        barModel.setData(data);

        // Options
        BarChartOptions options = new BarChartOptions();
        CartesianScales cScales = new CartesianScales();
        CartesianLinearAxes linearAxes = new CartesianLinearAxes();
        linearAxes.setOffset(true);
        cScales.addYAxesData(linearAxes);
        options.setScales(cScales);

        Title title = new Title();
        title.setDisplay(true);
        title.setText("Audit Actions");
        options.setTitle(title);

        barModel.setOptions(options);
    }
}
