package dev.lions.btpxpress.view;

import jakarta.annotation.PostConstruct;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

@Named("clientsView")
@ViewScoped
@Getter
@Setter
public class ClientsView extends BaseListView<ClientsView.Client, Long> implements Serializable {
    
    private static final Logger LOG = LoggerFactory.getLogger(ClientsView.class);

    private String filtreNom;
    private String filtreEmail;
    private String filtreVille;
    private Long clientId;

    @PostConstruct
    public void init() {
        loadItems();
    }

    @Override
    public void loadItems() {
        loading = true;
        try {
            items = new ArrayList<>();
            for (int i = 1; i <= 25; i++) {
                Client c = new Client();
                c.setId((long) i);
                c.setRaisonSociale("Entreprise " + i);
                c.setNomContact("Contact " + i);
                c.setEmail("contact" + i + "@example.com");
                c.setTelephone("+33 1 " + String.format("%02d", i) + " " + 
                               String.format("%02d", i * 2) + " " + 
                               String.format("%02d", i * 3) + " " + 
                               String.format("%02d", i * 4));
                c.setAdresse(i + " Rue Client, " + (75000 + i) + " Paris");
                c.setVille("Paris");
                c.setCodePostal(String.valueOf(75000 + i));
                c.setNombreChantiers(i % 5 + 1);
                c.setChiffreAffairesTotal(i * 25000.0);
                c.setDateCreation(LocalDateTime.now().minusDays(i * 30));
                items.add(c);
            }
            applyFilters(items, buildFilters());
        } catch (Exception e) {
            LOG.error("Erreur chargement clients", e);
        } finally {
            loading = false;
        }
    }

    private List<Predicate<Client>> buildFilters() {
        List<Predicate<Client>> filters = new ArrayList<>();
        if (filtreNom != null && !filtreNom.trim().isEmpty()) {
            filters.add(c -> c.getRaisonSociale().toLowerCase().contains(filtreNom.toLowerCase()) ||
                           c.getNomContact().toLowerCase().contains(filtreNom.toLowerCase()));
        }
        if (filtreEmail != null && !filtreEmail.trim().isEmpty()) {
            filters.add(c -> c.getEmail().toLowerCase().contains(filtreEmail.toLowerCase()));
        }
        if (filtreVille != null && !filtreVille.trim().isEmpty()) {
            filters.add(c -> c.getVille().toLowerCase().contains(filtreVille.toLowerCase()));
        }
        return filters;
    }

    @Override
    protected void resetFilterFields() {
        filtreNom = null;
        filtreEmail = null;
        filtreVille = null;
    }

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

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

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

    /**
     * Initialise un nouveau client pour la création.
     */
    @Override
    public String createNew() {
        selectedItem = new Client();
        return getCreatePath() + "?faces-redirect=true";
    }

    /**
     * Sauvegarde un nouveau client.
     */
    public String saveNew() {
        if (selectedItem == null) {
            selectedItem = new Client();
        }
        selectedItem.setId(System.currentTimeMillis());
        selectedItem.setDateCreation(LocalDateTime.now());
        selectedItem.setDateModification(LocalDateTime.now());
        selectedItem.setNombreChantiers(0);
        selectedItem.setChiffreAffairesTotal(0.0);
        items.add(selectedItem);
        LOG.info("Nouveau client créé : {}", selectedItem.getRaisonSociale());
        return "/clients?faces-redirect=true";
    }

    /**
     * Affiche les détails d'un client.
     */
    public String viewDetails(Long id) {
        selectedItem = items.stream()
                .filter(c -> c.getId().equals(id))
                .findFirst()
                .orElse(null);
        if (selectedItem != null) {
            return getDetailsPath() + "details?id=" + id + "&faces-redirect=true";
        }
        return "/clients?faces-redirect=true";
    }

    /**
     * Charge un client par son ID depuis les paramètres de la requête.
     */
    public void loadClientById() {
        if (clientId != null) {
            loadItems(); // S'assurer que les items sont chargés
            selectedItem = items.stream()
                    .filter(c -> c.getId().equals(clientId))
                    .findFirst()
                    .orElse(null);
            if (selectedItem == null) {
                LOG.warn("Client avec ID {} non trouvé", clientId);
            }
        }
    }

    @lombok.Getter
    @lombok.Setter
    public static class Client {
        private Long id;
        private String raisonSociale;
        private String nomContact;
        private String email;
        private String telephone;
        private String adresse;
        private String ville;
        private String codePostal;
        private String pays;
        private int nombreChantiers;
        private double chiffreAffairesTotal;
        private LocalDateTime dateCreation;
        private LocalDateTime dateModification;
    }
}
