'use client'
import React, { useState, useEffect } from 'react';
import StructureManagement from '@/components/Structure/Configuration/StructureManagement';
import ScheduleManagement from '@/components/Structure/Planning/ScheduleManagement';
import FeesManagement from '@/components/Structure/Tarification/FeesManagement';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import { useCsrfToken } from '@/context/CsrfContext';
import { ClassesProvider } from '@/context/ClassesContext';
import { createDatas,
  updateDatas,
  removeDatas,
  fetchSpecialities,
  fetchTeachers,
  fetchClasses,
  fetchSchedules,
  fetchRegistrationDiscounts,
  fetchTuitionDiscounts,
  fetchRegistrationFees,
  fetchTuitionFees,
  fetchRegistrationPaymentPlans,
  fetchTuitionPaymentPlans,
  fetchRegistrationPaymentModes,
  fetchTuitionPaymentModes } from '@/app/actions/schoolAction';
import SidebarTabs from '@/components/SidebarTabs';
import FilesGroupsManagement from '@/components/Structure/Files/FilesGroupsManagement';
import {
  fetchRegistrationTemplateMaster
} from "@/app/actions/registerFileGroupAction";
import logger from '@/utils/logger';
import { useEstablishment } from '@/context/EstablishmentContext';

export default function Page() {
  const [specialities, setSpecialities] = useState([]);
  const [classes, setClasses] = useState([]);
  const [teachers, setTeachers] = useState([]);
  const [schedules, setSchedules] = useState([]);
  const [registrationDiscounts, setRegistrationDiscounts] = useState([]);
  const [tuitionDiscounts, setTuitionDiscounts] = useState([]);
  const [registrationFees, setRegistrationFees] = useState([]);
  const [tuitionFees, setTuitionFees] = useState([]);
  const [fichiers, setFichiers] = useState([]);
  const [registrationPaymentPlans, setRegistrationPaymentPlans] = useState([]);
  const [tuitionPaymentPlans, setTuitionPaymentPlans] = useState([]);
  const [registrationPaymentModes, setRegistrationPaymentModes] = useState([]);
  const [tuitionPaymentModes, setTuitionPaymentModes] = useState([]);

  const csrfToken = useCsrfToken();
  const { selectedEstablishmentId } = useEstablishment();

  useEffect(() => {
    if (selectedEstablishmentId) {
      // Fetch data for specialities
      handleSpecialities();

      // Fetch data for teachers
      handleTeachers();

      // Fetch data for classes
      handleClasses();

      // Fetch data for schedules
      handleSchedules();

      // Fetch data for registration discounts
      handleRegistrationDiscounts();

      // Fetch data for tuition discounts
      handleTuitionDiscounts();

      // Fetch data for registration fees
      handleRegistrationFees();

      // Fetch data for tuition fees
      handleTuitionFees();

      // Fetch data for registration file templates
      fetchRegistrationTemplateMaster()
      .then((data)=> {
          setFichiers(data)
        })
      .catch(error => logger.error('Error fetching files:', error));

      // Fetch data for registration payment plans
      handleRegistrationPaymentPlans();

      // Fetch data for tuition payment plans
      handleTuitionPaymentPlans();

      // Fetch data for registration payment modes
      handleRegistrationPaymentModes();

      // Fetch data for tuition payment modes
      handleTuitionPaymentModes();
    }
  }, [selectedEstablishmentId]);

  const handleSpecialities = () => {
    fetchSpecialities(selectedEstablishmentId)
      .then(data => {
        setSpecialities(data);
      })
      .catch(error => logger.error('Error fetching specialities:', error));
  };

  const handleTeachers = () => {
    fetchTeachers(selectedEstablishmentId)
      .then(data => {
        setTeachers(data);
      })
      .catch(error => logger.error('Error fetching teachers:', error));
  };

  const handleClasses = () => {
    fetchClasses(selectedEstablishmentId)
      .then(data => {
        setClasses(data);
      })
      .catch(error => logger.error('Error fetching classes:', error));
  };

  const handleSchedules = () => {
    fetchSchedules()
      .then(data => {
        setSchedules(data);
      })
      .catch(error => logger.error('Error fetching schedules:', error));
  };

  const handleRegistrationDiscounts = () => {
    fetchRegistrationDiscounts(selectedEstablishmentId)
      .then(data => {
        setRegistrationDiscounts(data);
      })
      .catch(error => logger.error('Error fetching registration discounts:', error));
  };

  const handleTuitionDiscounts = () => {
    fetchTuitionDiscounts(selectedEstablishmentId)
      .then(data => {
        setTuitionDiscounts(data);
      })
      .catch(error => logger.error('Error fetching tuition discounts:', error));
  };

  const handleRegistrationFees = () => {
    fetchRegistrationFees(selectedEstablishmentId)
      .then(data => {
        setRegistrationFees(data);
      })
      .catch(error => logger.error('Error fetching registration fees:', error));
  };

  const handleTuitionFees = () => {
    fetchTuitionFees(selectedEstablishmentId)
      .then(data => {
        setTuitionFees(data);
      })
      .catch(error => logger.error('Error fetching tuition fees', error));
  };

  const handleRegistrationPaymentPlans = () => {
    fetchRegistrationPaymentPlans(selectedEstablishmentId)
      .then(data => {
        setRegistrationPaymentPlans(data);
      })
      .catch(error => logger.error('Error fetching registration payment plans:', error));
  };

  const handleTuitionPaymentPlans = () => {
    fetchTuitionPaymentPlans(selectedEstablishmentId)
      .then(data => {
        setTuitionPaymentPlans(data);
      })
      .catch(error => logger.error('Error fetching tuition payment plans:', error));
  };

  const handleRegistrationPaymentModes = () => {
    fetchRegistrationPaymentModes(selectedEstablishmentId)
      .then(data => {
        setRegistrationPaymentModes(data);
      })
      .catch(error => logger.error('Error fetching registration payment modes:', error));
  };

  const handleTuitionPaymentModes = () => {
    fetchTuitionPaymentModes(selectedEstablishmentId)
      .then(data => {
        setTuitionPaymentModes(data);
      })
      .catch(error => logger.error('Error fetching tuition payment modes:', error));
  };

  const handleCreate = (url, newData, setDatas) => {
    return createDatas(url, newData, csrfToken)
    .then(data => {
      setDatas(prevState => [...prevState, data]);
      return data;
    })
    .catch(error => {
      logger.error('Error creating data:', error);
      throw error;
    });
  };

  const handleEdit = (url, id, updatedData, setDatas) => {
    return updateDatas(url, id, updatedData, csrfToken)
    .then(data => {
      setDatas(prevState => prevState.map(item => item.id === id ? data : item));
      return data;
    })
    .catch(error => {
      logger.error('Error editing data:', error);
      throw error;
    });
  };

  const handleDelete = (url, id, setDatas) => {
    return removeDatas(url, id, csrfToken)
    .then(data => {
      setDatas(prevState => prevState.filter(item => item.id !== id));
      return data;
    })
    .catch(error => {
      logger.error('Error deleting data:', error);
      throw error;
    });
  };

  const handleUpdatePlanning = (url, planningId, updatedData) => {
    fetch(`${url}/${planningId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrfToken
      },
      body: JSON.stringify(updatedData),
      credentials: 'include'
    })
    .then(response => response.json())
    .then(data => {
      logger.debug('Planning mis à jour avec succès :', data);
      //setDatas(data);
    })
    .catch(error => {
      logger.error('Erreur :', error);
    });
  };

  const tabs = [
    {
      id: 'Configuration',
      label: "Configuration de l'école",
      content: (
        <StructureManagement
          specialities={specialities}
          setSpecialities={setSpecialities}
          teachers={teachers}
          setTeachers={setTeachers}
          classes={classes}
          setClasses={setClasses}
          handleCreate={handleCreate}
          handleEdit={handleEdit}
          handleDelete={handleDelete}
        />
      )
    },
    {
      id: 'Schedule',
      label: "Gestion de l'emploi du temps",
      content: (
        <ClassesProvider>
          <ScheduleManagement
            handleUpdatePlanning={handleUpdatePlanning}
            classes={classes}
          />
        </ClassesProvider>
      )
    },
    {
      id: 'Fees',
      label: 'Tarifications',
      content: (
        <FeesManagement
          registrationDiscounts={registrationDiscounts}
          setRegistrationDiscounts={setRegistrationDiscounts}
          tuitionDiscounts={tuitionDiscounts}
          setTuitionDiscounts={setTuitionDiscounts}
          registrationFees={registrationFees}
          setRegistrationFees={setRegistrationFees}
          tuitionFees={tuitionFees}
          setTuitionFees={setTuitionFees}
          registrationPaymentPlans={registrationPaymentPlans}
          setRegistrationPaymentPlans={setRegistrationPaymentPlans}
          tuitionPaymentPlans={tuitionPaymentPlans}
          setTuitionPaymentPlans={setTuitionPaymentPlans}
          registrationPaymentModes={registrationPaymentModes}
          setRegistrationPaymentModes={setRegistrationPaymentModes}
          tuitionPaymentModes={tuitionPaymentModes}
          setTuitionPaymentModes={setTuitionPaymentModes}
          handleCreate={handleCreate}
          handleEdit={handleEdit}
          handleDelete={handleDelete}
        />
      )
    },
    {
      id: 'Files',
      label: 'Documents d\'inscription',
      content: <FilesGroupsManagement csrfToken={csrfToken} selectedEstablishmentId={selectedEstablishmentId} />
    }
  ];

  return (
    <div className='p-8'>
      <DjangoCSRFToken csrfToken={csrfToken} />

      <div className="w-full p-4">
        <SidebarTabs tabs={tabs} />
      </div>

    </div>
  );
}
