'use client';
import React, { createContext, useContext, useState, useMemo } from 'react';
import { getCurrentSchoolYear, getNextSchoolYear, getHistoricalYears } from '@/utils/Date';
import { CURRENT_YEAR_FILTER, NEXT_YEAR_FILTER, HISTORICAL_FILTER } from '@/utils/constants';

const SchoolYearFilterContext = createContext(null);

/**
 * Provider pour le filtre d'année scolaire partagé entre plusieurs composants.
 * Permet d'avoir un seul filtre qui s'applique sur plusieurs tableaux.
 */
export const SchoolYearFilterProvider = ({ children }) => {
  const [activeYearFilter, setActiveYearFilter] = useState(CURRENT_YEAR_FILTER);
  
  const currentSchoolYear = useMemo(() => getCurrentSchoolYear(), []);
  const nextSchoolYear = useMemo(() => getNextSchoolYear(), []);
  const historicalYears = useMemo(() => getHistoricalYears(5), []);

  /**
   * Retourne l'année scolaire sélectionnée selon le filtre actif.
   */
  const selectedSchoolYear = useMemo(() => {
    if (activeYearFilter === CURRENT_YEAR_FILTER) return currentSchoolYear;
    if (activeYearFilter === NEXT_YEAR_FILTER) return nextSchoolYear;
    return historicalYears[0];
  }, [activeYearFilter, currentSchoolYear, nextSchoolYear, historicalYears]);

  /**
   * Filtre un tableau d'éléments par année scolaire.
   * @param {Array} items - Les éléments à filtrer
   * @param {string} yearField - Le nom du champ contenant l'année scolaire (défaut: 'school_year')
   */
  const filterByYear = useMemo(() => (items, yearField = 'school_year') => {
    if (!items) return [];
    if (activeYearFilter === CURRENT_YEAR_FILTER) {
      return items.filter((item) => item[yearField] === currentSchoolYear);
    } else if (activeYearFilter === NEXT_YEAR_FILTER) {
      return items.filter((item) => item[yearField] === nextSchoolYear);
    } else if (activeYearFilter === HISTORICAL_FILTER) {
      return items.filter((item) => historicalYears.includes(item[yearField]));
    }
    return items;
  }, [activeYearFilter, currentSchoolYear, nextSchoolYear, historicalYears]);

  /**
   * Calcule les compteurs pour chaque filtre.
   * @param {Array} items - Les éléments à compter
   * @param {string} yearField - Le nom du champ contenant l'année scolaire
   */
  const getYearCounts = useMemo(() => (items, yearField = 'school_year') => {
    if (!items) return { currentYear: 0, nextYear: 0, historical: 0 };
    return {
      currentYear: items.filter((item) => item[yearField] === currentSchoolYear).length,
      nextYear: items.filter((item) => item[yearField] === nextSchoolYear).length,
      historical: items.filter((item) => historicalYears.includes(item[yearField])).length,
    };
  }, [currentSchoolYear, nextSchoolYear, historicalYears]);

  const value = {
    activeYearFilter,
    setActiveYearFilter,
    currentSchoolYear,
    nextSchoolYear,
    historicalYears,
    selectedSchoolYear,
    filterByYear,
    getYearCounts,
  };

  return (
    <SchoolYearFilterContext.Provider value={value}>
      {children}
    </SchoolYearFilterContext.Provider>
  );
};

export const useSchoolYearFilter = () => {
  const context = useContext(SchoolYearFilterContext);
  if (!context) {
    throw new Error('useSchoolYearFilter must be used within a SchoolYearFilterProvider');
  }
  return context;
};

export default SchoolYearFilterContext;
