'use client';
import React, { useState, useEffect } from 'react';
import { getCurrentSchoolYear } from '@/utils/Date';

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,
  fetchRegistrationDiscounts,
  fetchTuitionDiscounts,
  fetchRegistrationFees,
  fetchTuitionFees,
  fetchRegistrationPaymentPlans,
  fetchTuitionPaymentPlans,
  fetchRegistrationPaymentModes,
  fetchTuitionPaymentModes,
  fetchEstablishmentCompetencies,
} from '@/app/actions/schoolAction';
import { fetchProfiles } from '@/app/actions/authAction';
import SidebarTabs from '@/components/SidebarTabs';
import FilesGroupsManagement from '@/components/Structure/Files/FilesGroupsManagement';
import { fetchRegistrationSchoolFileMasters } from '@/app/actions/registerFileGroupAction';
import logger from '@/utils/logger';
import { useEstablishment } from '@/context/EstablishmentContext';
import { PlanningProvider, PlanningModes } from '@/context/PlanningContext';
import { updatePlanning } from '@/app/actions/planningAction';
import CompetenciesList from '@/components/Structure/Competencies/CompetenciesList';

export default function Page() {
  const [specialities, setSpecialities] = useState([]);
  const [classes, setClasses] = useState([]);
  const [teachers, setTeachers] = 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 [profiles, setProfiles] = useState([]);
  const [establishmentCompetencies, setEstablishmentCompetencies] = useState(
    []
  );

  const csrfToken = useCsrfToken();
  const { selectedEstablishmentId, profileRole } = useEstablishment();
  const currentSchoolYear = getCurrentSchoolYear();

  const scheduleClasses = classes.filter(
    (classe) => classe?.school_year === currentSchoolYear
  );
  const scheduleSpecialities = specialities;
  const scheduleTeachers = teachers;

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

      // Fetch data for teachers
      handleTeachers();

      // Fetch data for classes
      handleClasses();

      // 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 schoolFileTemplates
      fetchRegistrationSchoolFileMasters(selectedEstablishmentId)
        .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();

      fetchProfiles()
        .then((data) => {
          setProfiles(data);
        })
        .catch((error) => {
          logger.error('Error fetching profileRoles:', error);
        });

      // Fetch data for establishment competencies
      handleEstablishmentCompetencies();
    }
  }, [selectedEstablishmentId]);

  const handleEstablishmentCompetencies = (cycle = 1) => {
    fetchEstablishmentCompetencies(selectedEstablishmentId, cycle)
      .then((data) => {
        setEstablishmentCompetencies(data);
      })
      .catch((error) =>
        logger.error('Error fetching setEstablishmentCompetencies:', error)
      );
  };

  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 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 = (planningId, updatedData) => {
    updatePlanning(planningId, updatedData, csrfToken)
      .then((data) => {
        logger.debug('Planning mis à jour avec succès :', data);
      })
      .catch((error) => {
        logger.error('Erreur :', error);
      });
  };

  const tabs = [
    {
      id: 'Configuration',
      label: 'Classes',
      content: (
        <div className="h-full overflow-y-auto p-4">
          <StructureManagement
            specialities={specialities}
            setSpecialities={setSpecialities}
            teachers={teachers}
            setTeachers={setTeachers}
            classes={classes}
            setClasses={setClasses}
            profiles={profiles}
            handleCreate={handleCreate}
            handleEdit={handleEdit}
            handleDelete={handleDelete}
          />
        </div>
      ),
    },
    {
      id: 'Schedule',
      label: 'Emploi du temps',
      content: (
        <div className="h-full overflow-y-auto p-4">
          <ClassesProvider>
            <ScheduleManagement
              handleUpdatePlanning={handleUpdatePlanning}
              classes={scheduleClasses}
              specialities={scheduleSpecialities}
              teachers={scheduleTeachers}
            />
          </ClassesProvider>
        </div>
      ),
    },
    ...(profileRole !== 0
      ? [
          {
            id: 'Fees',
            label: 'Tarifs',
            content: (
              <div className="h-full overflow-y-auto p-4">
                <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}
                />
              </div>
            ),
          },
        ]
      : []),
    {
      id: 'Files',
      label: 'Documents',
      content: (
        <div className="h-full overflow-y-auto p-4">
          <FilesGroupsManagement
            csrfToken={csrfToken}
            selectedEstablishmentId={selectedEstablishmentId}
            profileRole={profileRole}
          />
        </div>
      ),
    },
    {
      id: 'Competencies',
      label: 'Compétences',
      content: (
        <div className="h-full overflow-y-auto p-4">
          <CompetenciesList
            establishmentCompetencies={establishmentCompetencies}
            onChangeCycle={handleEstablishmentCompetencies}
          />
        </div>
      ),
    },
  ];

  return (
    <>
      <PlanningProvider
        establishmentId={selectedEstablishmentId}
        modeSet={PlanningModes.CLASS_SCHEDULE}
      >
        <DjangoCSRFToken csrfToken={csrfToken} />
        <SidebarTabs tabs={tabs} />
      </PlanningProvider>
    </>
  );
}
