import React, { createContext, useState, useContext, useEffect } from 'react';
import { useClasses } from '@/context/ClassesContext';

const ClasseFormContext = createContext();

export const useClasseForm = () => useContext(ClasseFormContext);

export const ClasseFormProvider = ({ children, initialClasse }) => {
  const { getNiveauxLabels } = useClasses();
  const [formData, setFormData] = useState({});

  useEffect(() => {
    const plannings = initialClasse.plannings_read || [];

    const defaultEmploiDuTemps = {
        lundi: [],
        mardi: [],
        mercredi: [],
        jeudi: [],
        vendredi: [],
        samedi: [],
        dimanche: []
    };

    const generateEmploiDuTemps = (planningType) => {
        if (planningType === 1) {
            return defaultEmploiDuTemps;
        } else if (planningType === 2) {
            return {
                S1: { DateDebut: '', DateFin: '', ...defaultEmploiDuTemps },
                S2: { DateDebut: '', DateFin: '', ...defaultEmploiDuTemps },
            };
        } else if (planningType === 3) {
            return {
                T1: { DateDebut: '', DateFin: '', ...defaultEmploiDuTemps },
                T2: { DateDebut: '', DateFin: '', ...defaultEmploiDuTemps },
                T3: { DateDebut: '', DateFin: '', ...defaultEmploiDuTemps },
            };
        }
    };

    const newFormData = {
        atmosphere_name: initialClasse.atmosphere_name || '',
        age_range: initialClasse.age_range || '',
        number_of_students: initialClasse.number_of_students || '',
        teaching_language: initialClasse.teaching_language || 'Français',
        school_year: initialClasse.school_year || '',
        teachers: initialClasse.teachers || [],
        teachers_details: initialClasse.teachers_details || [],
        type: initialClasse.type || 1,
        time_range: initialClasse.time_range || ['08:30', '17:30'],
        opening_days: initialClasse.opening_days || [1, 2, 4, 5],
        levels: initialClasse.levels || [],
        // plannings: plannings.length ? plannings.map(planning => ({
        //     niveau: planning.planning.niveau,
        //     emploiDuTemps: planning.planning.emploiDuTemps
        // })) : (initialClasse.levels || []).map(niveau => ({
        //     niveau: niveau,
        //     emploiDuTemps: generateEmploiDuTemps(initialClasse.type || 1)
        // }))
    };

    setFormData(newFormData);
}, [initialClasse, getNiveauxLabels]);

  return (
    <ClasseFormContext.Provider value={{ formData, setFormData }}>
      {children}
    </ClasseFormContext.Provider>
  );
};

