import React, { createContext, useContext } from 'react';
import { School } from 'lucide-react';

const ClassesContext = createContext();

export const useClasses = () => useContext(ClassesContext);

export const ClassesProvider = ({ children }) => {
  const currentYear = new Date().getFullYear();

  const schoolYears = [
    {
      value: `${currentYear - 1}-${currentYear}`,
      label: `${currentYear - 1}-${currentYear}`,
    },
    {
      value: `${currentYear}-${currentYear + 1}`,
      label: `${currentYear}-${currentYear + 1}`,
    },
    {
      value: `${currentYear + 1}-${currentYear + 2}`,
      label: `${currentYear + 1}-${currentYear + 2}`,
    },
  ];

  const niveauxPremierCycle = [
    { id: 1, name: 'TPS', age: 2 },
    { id: 2, name: 'PS', age: 3 },
    { id: 3, name: 'MS', age: 4 },
    { id: 4, name: 'GS', age: 5 },
  ];

  const niveauxSecondCycle = [
    { id: 5, name: 'CP', age: 6 },
    { id: 6, name: 'CE1', age: 7 },
    { id: 7, name: 'CE2', age: 8 },
  ];

  const niveauxTroisiemeCycle = [
    { id: 8, name: 'CM1', age: 9 },
    { id: 9, name: 'CM2', age: 10 },
  ];

  const allNiveaux = [
    ...niveauxPremierCycle,
    ...niveauxSecondCycle,
    ...niveauxTroisiemeCycle,
  ];

  const getNiveauxLabels = (levels) => {
    return levels.map((niveauId) => {
      const niveau = allNiveaux.find((n) => n.id === niveauId);
      return niveau ? niveau.name : niveauId;
    });
  };

  const getNiveauLabel = (level) => {
    const niveau = allNiveaux.find((n) => n.id === level);
    return niveau ? niveau.name : 'Niveau inconnu';
  };

  const getNiveauxTabs = (levels) => {
    // Trier les levels par id
    const sortedNiveaux = levels.sort((a, b) => a - b);

    // Mapper les labels correspondants
    return sortedNiveaux.map((niveauId) => {
      const niveau = allNiveaux.find((n) => n.id === niveauId);
      return niveau
        ? { id: niveau.id, title: niveau.name, icon: School }
        : { id: 'unknown', title: 'Niveau inconnu', icon: null };
    });
  };

  const generateAgeToNiveaux = (minAge, maxAge) => {
    if (minAge === null || isNaN(minAge)) {
      return [];
    }

    return allNiveaux
      .filter(
        ({ age }) =>
          age === minAge ||
          (age >= minAge && maxAge !== null && !isNaN(maxAge) && age < maxAge)
      )
      .map(({ id }) => id);
  };

  const getNiveauNameById = (id) => {
    const niveau = allNiveaux.find((item) => item.id.toString() === id);
    return niveau ? niveau.name : '';
  };

  const getAmbianceText = (classe) => {
    const ambiance = classe.atmosphere_name ? classe.atmosphere_name : '';
    const trancheAge = classe.age_range ? `${classe.age_range} ans` : '';

    if (ambiance && trancheAge) {
      return `${ambiance} (${trancheAge})`;
    } else if (ambiance) {
      return ambiance;
    } else if (trancheAge) {
      return trancheAge;
    } else {
      return 'Non spécifié';
    }
  };

  const getAmbianceName = (classe) => {
    const ambiance = classe.atmosphere_name ? classe.atmosphere_name : '';

    if (ambiance) {
      return ambiance;
    } else {
      return 'Non spécifié';
    }
  };

  const groupSpecialitiesBySubject = (teachers) => {
    const groupedSpecialities = {};

    if (!teachers) return [];

    teachers.forEach((teacher) => {
      if (teacher && teacher.specialites) {
        teacher.specialites.forEach((specialite) => {
          if (!groupedSpecialities[specialite.id]) {
            groupedSpecialities[specialite.id] = {
              ...specialite,
              teachers: [`${teacher.nom} ${teacher.prenom}`],
            };
          } else {
            groupedSpecialities[specialite.id].teachers.push(
              `${teacher.nom} ${teacher.prenom}`
            );
          }
        });
      }
    });

    return Object.values(groupedSpecialities);
  };

  return (
    <ClassesContext.Provider
      value={{
        schoolYears,
        getNiveauxLabels,
        getNiveauLabel,
        getNiveauxTabs,
        generateAgeToNiveaux,
        niveauxPremierCycle,
        niveauxSecondCycle,
        niveauxTroisiemeCycle,
        allNiveaux,
        getAmbianceText,
        getAmbianceName,
        groupSpecialitiesBySubject,
        getNiveauNameById,
      }}
    >
      {children}
    </ClassesContext.Provider>
  );
};
