'use client';
import React, { useState, useEffect } from 'react';
import {
  fetchProfileRoles,
  updateProfileRoles,
  deleteProfileRoles,
} from '@/app/actions/authAction';
import { dissociateGuardian } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
import { useEstablishment } from '@/context/EstablishmentContext';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import { useCsrfToken } from '@/context/CsrfContext';
import ProfileDirectory from '@/components/ProfileDirectory';

export default function Page() {
  const [profileRoles, setProfileRoles] = useState([]);
  const [reloadFetch, setReloadFetch] = useState(false);

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

  useEffect(() => {
    if (selectedEstablishmentId) {
      // Fetch data for profileRoles
      handleProfiles();
    }
  }, [selectedEstablishmentId, reloadFetch]);

  const handleProfiles = () => {
    fetchProfileRoles(selectedEstablishmentId)
      .then((data) => {
        setProfileRoles(data);
      })
      .catch((error) => logger.error('Error fetching profileRoles:', error));
    setReloadFetch(false);
  };

  const handleEdit = (profileRole) => {
    const updatedData = { ...profileRole, is_active: !profileRole.is_active };
    return updateProfileRoles(profileRole.id, updatedData, csrfToken)
      .then((data) => {
        setProfileRoles((prevState) =>
          prevState.map((item) => (item.id === profileRole.id ? data : item))
        );
        return data;
      })
      .catch((error) => {
        logger.error('Error editing data:', error);
        throw error;
      });
  };

  const handleDelete = (id) => {
    return deleteProfileRoles(id, csrfToken)
      .then(() => {
        setProfileRoles((prevState) =>
          prevState.filter((item) => item.id !== id)
        );
        logger.debug('Profile deleted successfully:', id);
      })
      .catch((error) => {
        logger.error('Error deleting profile:', error);
        throw error;
      });
  };

  const handleDissociate = (studentId, guardianId) => {
    return dissociateGuardian(studentId, guardianId)
      .then((response) => {
        logger.debug('Guardian dissociated successfully:', guardianId);

        // Vérifier si le Guardian a été supprimé
        const isGuardianDeleted = response?.isGuardianDeleted;

        // Mettre à jour le modèle profileRoles
        setProfileRoles(
          (prevState) =>
            prevState
              .map((profileRole) => {
                if (profileRole.associated_person?.id === guardianId) {
                  if (isGuardianDeleted) {
                    // Si le Guardian est supprimé, retirer le profileRole
                    return null;
                  } else {
                    // Si le Guardian n'est pas supprimé, mettre à jour les élèves associés
                    const updatedStudents =
                      profileRole.associated_person.students.filter(
                        (student) => student.id !== studentId
                      );
                    return {
                      ...profileRole,
                      associated_person: {
                        ...profileRole.associated_person,
                        students: updatedStudents, // Mettre à jour les élèves associés
                      },
                    };
                  }
                }
                setReloadFetch(true);
                return profileRole; // Conserver les autres profileRoles
              })
              .filter(Boolean) // Supprimer les entrées nulles
        );
      })
      .catch((error) => {
        logger.error('Error dissociating guardian:', error);
        throw error;
      });
  };

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

      <div className="w-full p-4">
        <ProfileDirectory
          profileRoles={profileRoles}
          handleActivateProfile={handleEdit}
          handleDeleteProfile={handleDelete}
          handleDissociateGuardian={handleDissociate}
        />
      </div>
    </div>
  );
}
