package dev.lions.btpxpress.view;

import dev.lions.btpxpress.service.MaterielService;
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("materielView")
@ViewScoped
@Getter
@Setter
public class MaterielView extends BaseListView<MaterielView.Materiel, Long> {

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

    @Inject
    MaterielService materielService;

    private String filtreNom;
    private String filtreType;
    private String filtreStatut;
    private Long materielId;

    @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>> materielsData = materielService.getAllMateriels();

            for (Map<String, Object> data : materielsData) {
                Materiel m = new Materiel();

                m.setId(data.get("id") != null ? Long.valueOf(data.get("id").toString().hashCode()) : null);
                m.setNom((String) data.get("nom"));
                m.setMarque((String) data.get("marque"));
                m.setModele((String) data.get("modele"));
                m.setNumeroSerie((String) data.get("numeroSerie"));
                m.setType((String) data.get("type"));
                m.setStatut((String) data.get("statut"));

                // Valeur d'achat
                Object valeurObj = data.get("valeurAchat");
                if (valeurObj != null) {
                    m.setValeurAchat(valeurObj instanceof Number ?
                        ((Number) valeurObj).doubleValue() :
                        Double.parseDouble(valeurObj.toString()));
                } else {
                    m.setValeurAchat(0.0);
                }

                // Date d'achat
                if (data.get("dateAchat") != null) {
                    m.setDateAchat(LocalDate.parse(data.get("dateAchat").toString()));
                }

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

                items.add(m);
            }

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

    private List<Predicate<Materiel>> buildFilters() {
        List<Predicate<Materiel>> filters = new ArrayList<>();
        if (filtreNom != null && !filtreNom.trim().isEmpty()) {
            filters.add(m -> m.getNom().toLowerCase().contains(filtreNom.toLowerCase()));
        }
        if (filtreType != null && !filtreType.trim().isEmpty() && !"TOUS".equals(filtreType)) {
            filters.add(m -> m.getType() != null && m.getType().equals(filtreType));
        }
        if (filtreStatut != null && !filtreStatut.trim().isEmpty() && !"TOUS".equals(filtreStatut)) {
            filters.add(m -> m.getStatut().equals(filtreStatut));
        }
        return filters;
    }

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

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

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

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

    @Override
    protected Materiel createNewEntity() {
        Materiel materiel = new Materiel();
        materiel.setStatut("DISPONIBLE");
        materiel.setDateAchat(LocalDate.now());
        materiel.setValeurAchat(0.0);
        materiel.setDateCreation(LocalDateTime.now());
        return materiel;
    }

    @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(Materiel entity) {
        return entity.getId();
    }

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

    @lombok.Getter
    @lombok.Setter
    public static class Materiel {
        private Long id;
        private String nom;
        private String marque;
        private String modele;
        private String numeroSerie;
        private String type;
        private String statut;
        private double valeurAchat;
        private LocalDate dateAchat;
        private LocalDateTime dateCreation;
    }
}
