// components/filter/ItemsFilter.js

/**
 * Filtre les items par période
 * @param {Array} items - Liste des items à filtrer
 * @param {string|object} period - Période de filtre ('today', 'week', 'month', etc. ou { id: 'custom', start, end })
 * @param {string} dateField - Nom du champ date (default: 'date')
 * @returns {Array} Items filtrés
 */
export const filterItemByPeriod = (items, period, dateField = 'date') => {
  if (!items || items.length === 0) return [];
  
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  
  // Période personnalisée
  if (typeof period === 'object' && period.id === 'custom') {
    const startDate = new Date(period.start);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(period.end);
    endDate.setHours(23, 59, 59, 999);
    
    return items.filter(item => {
      const itemDate = new Date(item[dateField]);
      return itemDate >= startDate && itemDate <= endDate;
    });
  }
  
  // Périodes prédéfinies
  let startDate, endDate;
  
  switch (period) {
    case 'today':
      startDate = today;
      endDate = new Date(today);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'week':
      // Début de la semaine (lundi)
      const dayOfWeek = today.getDay();
      const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
      startDate = new Date(today);
      startDate.setDate(today.getDate() - diffToMonday);
      endDate = new Date(startDate);
      endDate.setDate(startDate.getDate() + 6);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'month':
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
      break;
      
    case 'last_month':
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      endDate = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
      break;
      
    case 'quarter':
      const currentQuarter = Math.floor(now.getMonth() / 3);
      startDate = new Date(now.getFullYear(), currentQuarter * 3, 1);
      endDate = new Date(now.getFullYear(), currentQuarter * 3 + 3, 0, 23, 59, 59, 999);
      break;
      
    case 'year':
      startDate = new Date(now.getFullYear(), 0, 1);
      endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
      break;
      
    case '30days':
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 30);
      endDate = new Date(today);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case '90days':
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 90);
      endDate = new Date(today);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'all':
    default:
      return items;
  }
  
  return items.filter(item => {
    const itemDate = new Date(item[dateField]);
    return itemDate >= startDate && itemDate <= endDate;
  });
};

/**
 * Récupère les items de la période précédente (pour comparaison)
 * @param {Array} items - Liste des items
 * @param {string|object} period - Période actuelle
 * @param {string} dateField - Nom du champ date
 * @returns {Array} Items de la période précédente
 */
export const getPreviousPeriodItems = (items, period, dateField = 'date') => {
  if (!items || items.length === 0) return [];
  
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  
  // Période personnalisée - calculer la période précédente de même durée
  if (typeof period === 'object' && period.id === 'custom') {
    const startDate = new Date(period.start);
    const endDate = new Date(period.end);
    const duration = endDate.getTime() - startDate.getTime();
    
    const previousEnd = new Date(startDate.getTime() - 1); // Jour avant le début
    previousEnd.setHours(23, 59, 59, 999);
    
    const previousStart = new Date(previousEnd.getTime() - duration);
    previousStart.setHours(0, 0, 0, 0);
    
    return items.filter(item => {
      const itemDate = new Date(item[dateField]);
      return itemDate >= previousStart && itemDate <= previousEnd;
    });
  }
  
  let startDate, endDate;
  
  switch (period) {
    case 'today':
      // Hier
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 1);
      endDate = new Date(startDate);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'week':
      // Semaine précédente
      const dayOfWeek = today.getDay();
      const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
      startDate = new Date(today);
      startDate.setDate(today.getDate() - diffToMonday - 7);
      endDate = new Date(startDate);
      endDate.setDate(startDate.getDate() + 6);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'month':
      // Mois précédent
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      endDate = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
      break;
      
    case 'last_month':
      // Mois d'avant le mois dernier
      startDate = new Date(now.getFullYear(), now.getMonth() - 2, 1);
      endDate = new Date(now.getFullYear(), now.getMonth() - 1, 0, 23, 59, 59, 999);
      break;
      
    case 'quarter':
      // Trimestre précédent
      const currentQuarter = Math.floor(now.getMonth() / 3);
      startDate = new Date(now.getFullYear(), (currentQuarter - 1) * 3, 1);
      endDate = new Date(now.getFullYear(), currentQuarter * 3, 0, 23, 59, 59, 999);
      break;
      
    case 'year':
      // Année précédente
      startDate = new Date(now.getFullYear() - 1, 0, 1);
      endDate = new Date(now.getFullYear() - 1, 11, 31, 23, 59, 59, 999);
      break;
      
    case '30days':
      // 30 jours avant les 30 derniers jours
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 60);
      endDate = new Date(today);
      endDate.setDate(today.getDate() - 31);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case '90days':
      // 90 jours avant les 90 derniers jours
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 180);
      endDate = new Date(today);
      endDate.setDate(today.getDate() - 91);
      endDate.setHours(23, 59, 59, 999);
      break;
      
    case 'all':
    default:
      return [];
  }
  
  return items.filter(item => {
    const itemDate = new Date(item[dateField]);
    return itemDate >= startDate && itemDate <= endDate;
  });
};

/**
 * Obtient le label de la période
 * @param {string|object} period - Période
 * @returns {string} Label formaté
 */
export const getPeriodLabel = (period) => {
  if (typeof period === 'object' && period.id === 'custom') {
    const formatDate = (dateStr) => {
      const d = new Date(dateStr);
      return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
    };
    return `${formatDate(period.start)} - ${formatDate(period.end)}`;
  }
  
  const labels = {
    today: "Aujourd'hui",
    week: 'Cette semaine',
    month: 'Ce mois-ci',
    last_month: 'Mois dernier',
    quarter: 'Ce trimestre',
    year: 'Cette année',
    '30days': '30 derniers jours',
    '90days': '90 derniers jours',
    all: 'Tout',
  };
  
  return labels[period] || 'Période';
};