package dev.lions.btpxpress.view;

import dev.lions.btpxpress.service.EmployeService;
import jakarta.annotation.PostConstruct;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

@Named("employeView")
@ViewScoped
@Getter
@Setter
public class EmployeView extends BaseListView<EmployeView.Employe, Long> {

    private static final Logger LOG = LoggerFactory.getLogger(EmployeView.class);

    @Inject
    EmployeService employeService;

    private String filtreNom;
    private String filtrePoste;
    private String filtreStatut;
    private Long employeId;

    @PostConstruct
    public void init() {
        if (filtreStatut == null) {
            filtreStatut = "TOUS";
        }
        loadItems();
    }

    public void setFiltreStatut(String statut) {
        this.filtreStatut = statut;
    }

    @Override
    public void loadItems() {
        loading = true;
        try {
            items = new ArrayList<>();

            // Récupération depuis l'API backend
            List<Map<String, Object>> employesData = employeService.getAllEmployes();

            for (Map<String, Object> data : employesData) {
                Employe e = new Employe();

                e.setId(data.get("id") != null ? Long.valueOf(data.get("id").toString().hashCode()) : null);

                String nom = (String) data.get("nom");
                String prenom = (String) data.get("prenom");
                e.setNomComplet((prenom != null ? prenom + " " : "") + (nom != null ? nom : ""));

                e.setEmail((String) data.get("email"));
                e.setTelephone((String) data.get("telephone"));
                e.setPoste((String) data.get("poste"));
                e.setStatut((String) data.get("statut"));

                // Taux horaire
                Object tauxObj = data.get("tauxHoraire");
                if (tauxObj != null) {
                    e.setTauxHoraire(tauxObj instanceof Number ?
                        ((Number) tauxObj).doubleValue() :
                        Double.parseDouble(tauxObj.toString()));
                } else {
                    e.setTauxHoraire(0.0);
                }

                // Date d'embauche
                if (data.get("dateEmbauche") != null) {
                    e.setDateEmbauche(LocalDate.parse(data.get("dateEmbauche").toString()));
                }

                if (data.get("dateCreation") != null) {
                    e.setDateCreation(LocalDateTime.parse(data.get("dateCreation").toString()));
                }

                items.add(e);
            }

            LOG.info("Employés chargés depuis l'API : {} élément(s)", items.size());
            applyFilters(items, buildFilters());
        } catch (Exception e) {
            LOG.error("Erreur chargement employés depuis l'API", e);
            items = new ArrayList<>();
        } finally {
            loading = false;
        }
    }

    private List<Predicate<Employe>> buildFilters() {
        List<Predicate<Employe>> filters = new ArrayList<>();
        if (filtreNom != null && !filtreNom.trim().isEmpty()) {
            filters.add(e -> e.getNomComplet().toLowerCase().contains(filtreNom.toLowerCase()));
        }
        if (filtrePoste != null && !filtrePoste.trim().isEmpty()) {
            filters.add(e -> e.getPoste() != null && e.getPoste().toLowerCase().contains(filtrePoste.toLowerCase()));
        }
        if (filtreStatut != null && !filtreStatut.trim().isEmpty() && !"TOUS".equals(filtreStatut)) {
            filters.add(e -> e.getStatut().equals(filtreStatut));
        }
        return filters;
    }

    @Override
    protected void resetFilterFields() {
        filtreNom = null;
        filtrePoste = null;
        filtreStatut = "TOUS";
    }

    @Override
    protected String getDetailsPath() {
        return "/employes/";
    }

    @Override
    protected String getCreatePath() {
        return "/employes/nouveau";
    }

    @Override
    protected void performDelete() {
        LOG.info("Suppression employé : {}", selectedItem.getId());
    }

    @Override
    protected Employe createNewEntity() {
        Employe employe = new Employe();
        employe.setStatut("ACTIF");
        employe.setDateEmbauche(LocalDate.now());
        employe.setTauxHoraire(0.0);
        employe.setDateCreation(LocalDateTime.now());
        return employe;
    }

    @Override
    protected void performCreate() {
        if (selectedItem.getId() == null) {
            selectedItem.setId(System.currentTimeMillis());
        }
        selectedItem.setDateCreation(LocalDateTime.now());
        items.add(selectedItem);
        LOG.info("Created: {}", selectedItem);
    }

    @Override
    protected void performUpdate() {
        LOG.info("Updated: {}", selectedItem);
    }

    @Override
    protected Long getEntityId(Employe entity) {
        return entity.getId();
    }

    @Override
    public String createNew() {
        selectedItem = new Employe();
        selectedItem.setStatut("ACTIF");
        selectedItem.setDateEmbauche(LocalDate.now());
        return getCreatePath() + "?faces-redirect=true";
    }

    @lombok.Getter
    @lombok.Setter
    public static class Employe {
        private Long id;
        private String nomComplet;
        private String email;
        private String telephone;
        private String poste;
        private String statut;
        private double tauxHoraire;
        private LocalDate dateEmbauche;
        private LocalDateTime dateCreation;
    }
}
