package com.gbcm.client.beans;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.gbcm.client.service.DashboardRestService;

import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

@Named("dashboardBean")
@RequestScoped
public class DashboardBean implements Serializable {

    @Inject
    private DashboardRestService dashboardRestService;

    // Propriétés pour les filtres et sélections
    private String revenuePeriod = "30d";

    // Cache des métriques pour la requête
    private Map<String, Object> metrics;
    private Map<String, Object> clientMetrics;
    private Map<String, Object> sessionMetrics;
    private Map<String, Object> workshopMetrics;
    private Map<String, Object> financialMetrics;

    @SuppressWarnings("unchecked")
    @PostConstruct
    public void init() {
        try {
            metrics = dashboardRestService.getDashboardMetrics();
            if (metrics != null) {
                clientMetrics = (Map<String, Object>) metrics.get("clients");
                sessionMetrics = (Map<String, Object>) metrics.get("sessions");
                workshopMetrics = (Map<String, Object>) metrics.get("workshops");
                financialMetrics = (Map<String, Object>) metrics.get("financial");
            }
        } catch (Exception e) {
            // Fallback empty maps to avoid NPE
            clientMetrics = Map.of();
            sessionMetrics = Map.of();
            workshopMetrics = Map.of();
            financialMetrics = Map.of();
        }
    }

    /**
     * Classe pour représenter une activité récente
     */
    public static class Activity {
        private String icon;
        private String title;
        private String description;
        private String timestamp;

        public Activity(String icon, String title, String description, String timestamp) {
            this.icon = icon;
            this.title = title;
            this.description = description;
            this.timestamp = timestamp;
        }

        public String getIcon() {
            return icon;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

        public String getTimestamp() {
            return timestamp;
        }
    }

    /**
     * Classe pour représenter une tâche
     */
    public static class Task {
        private String title;
        private String description;
        private String clientName;
        private String priority;
        private String dueDate;
        private boolean completed;

        public Task(String title, String description, String clientName, String priority, String dueDate,
                boolean completed) {
            this.title = title;
            this.description = description;
            this.clientName = clientName;
            this.priority = priority;
            this.dueDate = dueDate;
            this.completed = completed;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

        public String getClientName() {
            return clientName;
        }

        public String getPriority() {
            return priority;
        }

        public String getDueDate() {
            return dueDate;
        }

        public boolean isCompleted() {
            return completed;
        }
    }

    public List<Activity> getRecentActivities() {
        // Activités simulées pour l'instant car pas d'historique d'activités en DB
        List<Activity> activities = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        activities.add(new Activity("pi pi-check", "Système prêt", "Transition vers Data Réelle effectuée",
                LocalDateTime.now().format(formatter)));
        return activities;
    }

    public int getActiveClientsCount() {
        return getIntMetric(clientMetrics, "activeClients");
    }

    public int getSessionsThisMonth() {
        return getIntMetric(sessionMetrics, "sessionsThisMonth");
    }

    public int getPlannedWorkshops() {
        // Using active or scheduled
        return getIntMetric(workshopMetrics, "activeWorkshops");
    }

    public String getMonthlyRevenue() {
        // From financial metrics
        if (financialMetrics != null && financialMetrics.get("monthlyRevenue") != null) {
            return "€" + financialMetrics.get("monthlyRevenue");
        }
        return "€0";
    }

    public String getClientsGrowth() {
        // Not calculated yet
        return "+0%";
    }

    public String getSessionsGrowth() {
        return "+0%";
    }

    public String getWorkshopsChange() {
        return "0%";
    }

    public String getRevenueGrowth() {
        return "+0%";
    }

    public List<Task> getTasks() {
        return new ArrayList<>(); // Empty tasks for now
    }

    public Object getRevenueChartModel() {
        return null;
    }

    public Object getClientTypeChartModel() {
        return null;
    }

    public String getRevenuePeriod() {
        return revenuePeriod;
    }

    public void setRevenuePeriod(String revenuePeriod) {
        this.revenuePeriod = revenuePeriod;
    }

    // Stats d'entreprise
    public int getEnterpriseClients() {
        // Can be approximate or estimated from total
        return getIntMetric(clientMetrics, "totalClients");
    }

    public int getIndividualClients() {
        return 0;
    }

    // KPIs
    public int getRevenueProgress() {
        return 0;
    }

    public int getClientProgress() {
        return 0;
    }

    public int getSessionProgress() {
        return 0;
    }

    public int getSatisfactionProgress() {
        return 0;
    }

    // Helpers
    private int getIntMetric(Map<String, Object> map, String key) {
        if (map != null && map.get(key) != null) {
            Object val = map.get(key);
            if (val instanceof Number) {
                return ((Number) val).intValue();
            }
        }
        return 0;
    }
}
