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 typeEmploiDuTemps = [
    { id: 1, label: 'Annuel' },
    { id: 2, label: 'Semestriel' },
    { id: 3, label: 'Trimestriel' },
  ];

  const selectedDays = {
    1: 'lundi',
    2: 'mardi',
    3: 'mercredi',
    4: 'jeudi',
    5: 'vendredi',
    6: 'samedi',
    7: 'dimanche',
  };

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

  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 updatePlannings = (formData, existingPlannings) => {
    return formData.levels.map((niveau) => {
      let existingPlanning = existingPlannings.find(
        (planning) => planning.niveau === niveau
      );

      const emploiDuTemps = formData.opening_days.reduce((acc, dayId) => {
        const dayName = selectedDays[dayId];
        if (dayName) {
          acc[dayName] = existingPlanning?.emploiDuTemps?.[dayName] || [];
        }
        return acc;
      }, {});

      let updatedPlanning;
      if (formData.type === 1) {
        updatedPlanning = {
          niveau: niveau,
          emploiDuTemps,
        };
      } else if (formData.type === 2) {
        updatedPlanning = {
          niveau: niveau,
          emploiDuTemps: {
            S1: {
              DateDebut: formData.date_debut_semestre_1,
              DateFin: formData.date_fin_semestre_1,
              ...emploiDuTemps,
            },
            S2: {
              DateDebut: formData.date_debut_semestre_2,
              DateFin: formData.date_fin_semestre_2,
              ...emploiDuTemps,
            },
          },
        };
      } else if (formData.type === 3) {
        updatedPlanning = {
          niveau: niveau,
          emploiDuTemps: {
            T1: {
              DateDebut: formData.date_debut_trimestre_1,
              DateFin: formData.date_fin_trimestre_1,
              ...emploiDuTemps,
            },
            T2: {
              DateDebut: formData.date_debut_trimestre_2,
              DateFin: formData.date_fin_trimestre_2,
              ...emploiDuTemps,
            },
            T3: {
              DateDebut: formData.date_debut_trimestre_3,
              DateFin: formData.date_fin_trimestre_3,
              ...emploiDuTemps,
            },
          },
        };
      }

      // Fusionner les plannings existants avec les nouvelles données
      return existingPlanning
        ? { ...existingPlanning, ...updatedPlanning }
        : updatedPlanning;
    });
  };

  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);
  };

  const determineInitialPeriod = (emploiDuTemps) => {
    if (emploiDuTemps.S1 && emploiDuTemps.S2) {
      return 'S1'; // Planning semestriel
    } else if (emploiDuTemps.T1 && emploiDuTemps.T2 && emploiDuTemps.T3) {
      return 'T1'; // Planning trimestriel
    }
    return ''; // Planning annuel ou autre
  };

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