'use client';
import React, { useState, useEffect } from 'react';
import Table from '@/components/Table';
import SidebarTabs from '@/components/SidebarTabs';
import Textarea from '@/components/Textarea';
import { useTranslations } from 'next-intl';
import StatusLabel from '@/components/StatusLabel';
import Popup from '@/components/Popup';
import Loader from '@/components/Loader';
import { useRouter } from 'next/navigation';
import {
  Search,
  Send,
  Edit,
  Archive,
  FileText,
  CheckCircle,
  Plus,
  Upload,
  Eye,
  XCircle,
  Download,
} from 'lucide-react';
import Modal from '@/components/Modal';
import { useEstablishment } from '@/context/EstablishmentContext';

import {
  fetchRegisterForms,
  sendRegisterForm,
  archiveRegisterForm,
  editRegisterForm,
} from '@/app/actions/subscriptionAction';

import { fetchClasses } from '@/app/actions/schoolAction';

import {
  FE_ADMIN_SUBSCRIPTIONS_EDIT_URL,
  FE_ADMIN_SUBSCRIPTIONS_VALIDATE_URL,
  FE_ADMIN_SUBSCRIPTIONS_CREATE_URL,
} from '@/utils/Url';
import { getSecureFileUrl } from '@/utils/fileUrl';

import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import { useCsrfToken } from '@/context/CsrfContext';
import logger from '@/utils/logger';
import { PhoneLabel } from '@/components/Form/PhoneLabel';
import FileUpload from '@/components/Form/FileUpload';
import FilesModal from '@/components/Inscription/FilesModal';
import { getCurrentSchoolYear, getNextSchoolYear } from '@/utils/Date';

import {
  RegistrationFormStatus,
  CURRENT_YEAR_FILTER,
  NEXT_YEAR_FILTER,
  HISTORICAL_FILTER,
} from '@/utils/constants';
import AlertMessage from '@/components/AlertMessage';
import EmptyState from '@/components/EmptyState';
import { useNotification } from '@/context/NotificationContext';
import { exportToCSV } from '@/utils/exportCSV';

export default function Page({ params: { locale } }) {
  const t = useTranslations('subscriptions');
  const [registrationForms, setRegistrationForms] = useState([]);
  const [
    registrationFormsDataCurrentYear,
    setRegistrationFormsDataCurrentYear,
  ] = useState([]);
  const [registrationFormsDataNextYear, setRegistrationFormsDataNextYear] =
    useState([]);
  const [registrationFormsDataHistorical, setRegistrationFormsDataHistorical] =
    useState([]);
  const currentSchoolYear = getCurrentSchoolYear();
  const nextSchoolYear = getNextSchoolYear();
  const [totalCurrentSchoolYearPages, setTotalCurrentSchoolYearPages] =
    useState(1);
  const [totalNextSchoolYearPages, setTotalNextSchoolYearPages] = useState(1);
  const [totalHistoricalPages, setTotalHistoricalPages] = useState(1);
  const [currentSchoolYearPage, setCurrentSchoolYearPage] = useState(1);
  const [currentSchoolNextYearPage, setCurrentSchoolNextYearPage] = useState(1);
  const [currentSchoolHistoricalYearPage, setCurrentSchoolHistoricalYearPage] =
    useState(1);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState(CURRENT_YEAR_FILTER);
  const [totalCurrentYear, setTotalCurrentYear] = useState(0);
  const [totalNextYear, setTotalNextYear] = useState(0);
  const [totalHistorical, setTotalHistorical] = useState(0);
  const [itemsPerPage, setItemsPerPage] = useState(10); // Définir le nombre d'éléments par page

  const [classes, setClasses] = useState([]);
  const [reloadFetch, setReloadFetch] = useState(false);

  const [isFilesModalOpen, setIsFilesModalOpen] = useState(false);
  const [selectedRegisterForm, setSelectedRegisterForm] = useState([]);

  const [confirmPopupVisible, setConfirmPopupVisible] = useState(false);
  const [confirmPopupMessage, setConfirmPopupMessage] = useState('');
  const [confirmPopupOnConfirm, setConfirmPopupOnConfirm] = useState(() => {});

  const [isSepaUploadModalOpen, setIsSepaUploadModalOpen] = useState(false);
  const [selectedRowForUpload, setSelectedRowForUpload] = useState(null);

  // Refus popup state
  const [isRefusePopupOpen, setIsRefusePopupOpen] = useState(false);
  const [refuseReason, setRefuseReason] = useState('');
  const [rowToRefuse, setRowToRefuse] = useState(null);
  // Ouvre la popup de refus
  const openRefusePopup = (row) => {
    setRowToRefuse(row);
    setRefuseReason('');
    setIsRefusePopupOpen(true);
  };

  // Valide le refus
  const handleRefuse = () => {
    if (!refuseReason.trim()) {
      showNotification(
        'Merci de préciser la raison du refus.',
        'error',
        'Erreur'
      );
      return;
    }
    const formData = new FormData();
    formData.append(
      'data',
      JSON.stringify({
        status: RegistrationFormStatus.STATUS_ARCHIVED,
        notes: refuseReason,
      })
    );

    editRegisterForm(rowToRefuse.student.id, formData, csrfToken)
      .then(() => {
        showNotification(
          'Le dossier a été refusé et archivé.',
          'success',
          'Succès'
        );
        setReloadFetch(true);
        setIsRefusePopupOpen(false);
      })
      .catch(() => {
        showNotification('Erreur lors du refus du dossier.', 'error', 'Erreur');
      });
  };

  const csrfToken = useCsrfToken();
  const router = useRouter();
  const { selectedEstablishmentId, profileRole } = useEstablishment();
  const { showNotification } = useNotification();

  const openSepaUploadModal = (row) => {
    setSelectedRowForUpload(row);
    setIsSepaUploadModalOpen(true);
  };

  const closeSepaUploadModal = () => {
    setSelectedRowForUpload(null);
    setIsSepaUploadModalOpen(false);
  };

  const openFilesModal = (row) => {
    setSelectedRegisterForm(row || []);
    setIsFilesModalOpen(true);
  };

  // Export CSV
  const handleExportCSV = () => {
    const dataToExport =
      activeTab === CURRENT_YEAR_FILTER
        ? registrationFormsDataCurrentYear
        : activeTab === NEXT_YEAR_FILTER
          ? registrationFormsDataNextYear
          : registrationFormsDataHistorical;

    const exportColumns = [
      {
        key: 'student',
        label: 'Nom',
        transform: (value) => value?.last_name || '',
      },
      {
        key: 'student',
        label: 'Prénom',
        transform: (value) => value?.first_name || '',
      },
      {
        key: 'student',
        label: 'Date de naissance',
        transform: (value) => value?.birth_date || '',
      },
      {
        key: 'student',
        label: 'Email contact',
        transform: (value) =>
          value?.guardians?.[0]?.associated_profile_email || '',
      },
      {
        key: 'student',
        label: 'Téléphone contact',
        transform: (value) => value?.guardians?.[0]?.phone || '',
      },
      {
        key: 'student',
        label: 'Nom responsable 1',
        transform: (value) => value?.guardians?.[0]?.last_name || '',
      },
      {
        key: 'student',
        label: 'Prénom responsable 1',
        transform: (value) => value?.guardians?.[0]?.first_name || '',
      },
      {
        key: 'student',
        label: 'Nom responsable 2',
        transform: (value) => value?.guardians?.[1]?.last_name || '',
      },
      {
        key: 'student',
        label: 'Prénom responsable 2',
        transform: (value) => value?.guardians?.[1]?.first_name || '',
      },
      { key: 'school_year', label: 'Année scolaire' },
      {
        key: 'status',
        label: 'Statut',
        transform: (value) => {
          const statusMap = {
            0: 'En attente',
            1: 'En cours',
            2: 'Envoyé',
            3: 'À relancer',
            4: 'À valider',
            5: 'Validé',
            6: 'Archivé',
          };
          return statusMap[value] || value;
        },
      },
      { key: 'formatted_last_update', label: 'Dernière mise à jour' },
    ];

    const yearLabel =
      activeTab === CURRENT_YEAR_FILTER
        ? currentSchoolYear
        : activeTab === NEXT_YEAR_FILTER
          ? nextSchoolYear
          : 'historique';
    const filename = `inscriptions_${yearLabel}_${new Date().toISOString().split('T')[0]}`;
    exportToCSV(dataToExport, exportColumns, filename);
  };

  const requestErrorHandler = (err) => {
    logger.error('Error fetching data:', err);
  };

  /**
   * Handles the pending data for the registration form.
   *
   * @param {Object} data - The data object containing registration forms and count.
   * @param {Array} data.registerForms - The array of registration forms.
   * @param {number} data.count - The total count of registration forms.
   */
  const registerFormCurrrentYearDataHandler = (data) => {
    if (data) {
      const { registerForms, count, page_size } = data;
      setRegistrationFormsDataCurrentYear(registerForms);

      const calculatedTotalPages =
        count === 0 ? count : Math.ceil(count / page_size);
      setTotalCurrentYear(count);
      setTotalCurrentSchoolYearPages(calculatedTotalPages);
    }
  };

  /**
   * Handles the data received from the subscription registration form.
   *
   * @param {Object} data - The data object received from the subscription registration form.
   * @param {Array} data.registerForms - An array of registration forms.
   * @param {number} data.count - The total count of subscribed forms.
   */
  const registerFormNextYearDataHandler = (data) => {
    if (data) {
      const { registerForms, count, page_size } = data;
      setRegistrationFormsDataNextYear(registerForms);

      const calculatedTotalPages =
        count === 0 ? count : Math.ceil(count / page_size);
      setTotalNextYear(count);
      setTotalNextSchoolYearPages(calculatedTotalPages);
    }
  };

  /**
   * Handles the archived data for the register form.
   *
   * @param {Object} data - The data object containing archived register forms and count.
   * @param {Array} data.registerForms - The array of archived register forms.
   * @param {number} data.count - The total count of archived register forms.
   */
  const registerFormHistoricalDataHandler = (data) => {
    if (data) {
      const { registerForms, count, page_size } = data;
      setRegistrationFormsDataHistorical(registerForms);

      const calculatedTotalPages =
        count === 0 ? count : Math.ceil(count / page_size);
      setTotalHistorical(count);
      setTotalHistoricalPages(calculatedTotalPages);
    }
  };

  useEffect(() => {
    if (selectedEstablishmentId) {
      const fetchDataAndSetState = () => {
        setIsLoading(true);
        Promise.all([
          fetchRegisterForms(
            selectedEstablishmentId,
            CURRENT_YEAR_FILTER,
            currentSchoolYearPage,
            itemsPerPage,
            searchTerm
          )
            .then(registerFormCurrrentYearDataHandler)
            .catch(requestErrorHandler),

          fetchClasses(selectedEstablishmentId)
            .then((classesData) => {
              setClasses(classesData);
            })
            .catch(requestErrorHandler),

          fetchRegisterForms(selectedEstablishmentId, NEXT_YEAR_FILTER)
            .then(registerFormNextYearDataHandler)
            .catch(requestErrorHandler),
          fetchRegisterForms(selectedEstablishmentId, HISTORICAL_FILTER)
            .then(registerFormHistoricalDataHandler)
            .catch(requestErrorHandler),
        ])
          .then(() => {
            setIsLoading(false);
            setReloadFetch(false);
          })
          .catch((err) => {
            logger.error(err);
            setIsLoading(false);
            setReloadFetch(false);
          });
      };

      fetchDataAndSetState();
    }
  }, [selectedEstablishmentId, reloadFetch]);

  useEffect(() => {
    if (selectedEstablishmentId) {
      const fetchDataAndSetState = () => {
        fetchRegisterForms(
          selectedEstablishmentId,
          CURRENT_YEAR_FILTER,
          currentSchoolYearPage,
          itemsPerPage,
          searchTerm
        )
          .then(registerFormCurrrentYearDataHandler)
          .catch(requestErrorHandler);
        fetchRegisterForms(selectedEstablishmentId, NEXT_YEAR_FILTER)
          .then(registerFormNextYearDataHandler)
          .catch(requestErrorHandler);
        fetchRegisterForms(selectedEstablishmentId, HISTORICAL_FILTER)
          .then(registerFormHistoricalDataHandler)
          .catch(requestErrorHandler);

        setReloadFetch(false);
      };

      const timeoutId = setTimeout(() => {
        fetchDataAndSetState();
      }, 500); // Debounce la recherche
      return () => clearTimeout(timeoutId);
    }
  }, [
    searchTerm,
    selectedEstablishmentId,
    currentSchoolYearPage,
    itemsPerPage,
  ]);

  /**
   * UseEffect to update page count of tab
   */
  useEffect(() => {
    if (activeTab === CURRENT_YEAR_FILTER) {
      setTotalCurrentSchoolYearPages(
        Math.ceil(totalCurrentYear / itemsPerPage)
      );
    } else if (activeTab === NEXT_YEAR_FILTER) {
      setTotalNextSchoolYearPages(Math.ceil(totalNextYear / itemsPerPage));
    } else if (activeTab === HISTORICAL_FILTER) {
      setTotalHistoricalPages(Math.ceil(totalHistorical / itemsPerPage));
    }
  }, [currentSchoolYearPage]);

  const handleSepaFileUpload = (file, row) => {
    if (!file || !row) {
      logger.error("Aucun fichier ou ligne sélectionnée pour l'upload.");
      return;
    }

    // Préparer les données JSON
    const jsonData = {
      status: 7,
    };

    const formData = new FormData();

    // Ajouter les données JSON sous forme de chaîne
    formData.append('data', JSON.stringify(jsonData));
    formData.append('sepa_file', file);

    // Appeler l'API pour uploader le fichier SEPA
    editRegisterForm(row.student.id, formData, csrfToken)
      .then((response) => {
        logger.debug('Mandat SEPA uploadé avec succès :', response);
        showNotification(
          'Le mandat SEPA a été uploadé avec succès.',
          'success',
          'Succès'
        );
        setReloadFetch(true);
        closeSepaUploadModal();
      })
      .catch((error) => {
        logger.error("Erreur lors de l'upload du mandat SEPA :", error);
        showNotification(
          "Erreur lors de l'upload du mandat SEPA.",
          'error',
          'Erreur'
        );
      });
  };

  /**
   * Archives a registration form after user confirmation.
   *
   * @param {number} id - The ID of the registration form to be archived.
   * @param {string} nom - The last name of the person whose registration form is being archived.
   * @param {string} prenom - The first name of the person whose registration form is being archived.
   */
  const archiveFicheInscription = (id, nom, prenom) => {
    setConfirmPopupMessage(
      `Attentions ! \nVous êtes sur le point d'archiver le dossier d'inscription de ${nom} ${prenom}\nÊtes-vous sûr(e) de vouloir poursuivre l'opération ?`
    );
    setConfirmPopupOnConfirm(() => () => {
      archiveRegisterForm(id)
        .then((data) => {
          logger.debug('Success:', data);
          showNotification(
            "Le dossier d'inscription a été correctement archivé",
            'success',
            'Succès'
          );
          setRegistrationForms(
            registrationForms.filter((fiche) => fiche.id !== id)
          );
          setReloadFetch(true);
        })
        .catch((error) => {
          showNotification(
            "Erreur lors de l'archivage du dossier d'inscription",
            'error',
            'Erreur'
          );
        });
      setConfirmPopupVisible(false);
    });
    setConfirmPopupVisible(true);
  };

  const sendConfirmRegisterForm = (id, nom, prenom) => {
    setConfirmPopupMessage(
      `Avertissement ! \nVous êtes sur le point d'envoyer un dossier d'inscription à ${nom} ${prenom}\nÊtes-vous sûr(e) de vouloir poursuivre l'opération ?`
    );
    setConfirmPopupOnConfirm(() => () => {
      sendRegisterForm(id)
        .then((data) => {
          logger.debug('Success:', data);
          showNotification(
            "Le dossier d'inscription a été envoyé avec succès",
            'success',
            'Succès'
          );
          setReloadFetch(true);
        })
        .catch((error) => {
          logger.error('Error archiving data:', error);
          showNotification(
            "Erreur lors de l'envoi du dossier d'inscription",
            'error',
            'Erreur'
          );
        });
      setConfirmPopupVisible(false);
    });
    setConfirmPopupVisible(true);
  };

  const updateStatusAction = (id, newStatus) => {
    logger.debug(
      `Mise à jour du statut du dossier d'inscription avec l'ID : ${id} vers le statut : ${newStatus}`
    );
  };

  const handleSearchChange = (event) => {
    setSearchTerm(event.target.value);
  };

  const handlePageChange = (newPage) => {
    if (activeTab === CURRENT_YEAR_FILTER) {
      setCurrentSchoolYearPage(newPage);
    } else if (activeTab === NEXT_YEAR_FILTER) {
      setCurrentSchoolNextYearPage(newPage);
    } else if (activeTab === HISTORICAL_FILTER) {
      setCurrentSchoolHistoricalYearPage(newPage);
    }
  };

  const getActionsByStatus = (row) => {
    const actions = {
      // Etat "A envoyer" :
      // - Editer le formulaire de création
      // - Envoyer le formulaire aux parents
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_TO_SEND]: [
        {
          icon: (
            <span title="Editer le formulaire de création">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_CREATE_URL}?id=${row.student.id}&school_year=${activeTab}`
            ),
        },
        {
          icon: (
            <span title="Envoyer le dossier">
              <Send className="w-5 h-5 text-primary hover:text-secondary" />
            </span>
          ),
          onClick: () =>
            sendConfirmRegisterForm(
              row.student.id,
              row.student.last_name,
              row.student.first_name
            ),
        },
      ],
      // Etat "En attente" :
      // - Editer le formulaire de création
      // - Renvoyer le formulaire aux parents
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_PENDING]: [
        {
          icon: (
            <span title="Editer le formulaire de création">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
            ),
        },
        {
          icon: (
            <span title="Renvoyer le dossier">
              <Send className="w-5 h-5 text-primary hover:text-secondary" />
            </span>
          ),
          onClick: () =>
            sendConfirmRegisterForm(
              row.student.id,
              row.student.last_name,
              row.student.first_name
            ),
        },
      ],
      // Etat "Signé" :
      // - Editer le formulaire d'inscription
      // - Visualiser les documents signés par les parents
      // - Valider le dossier d'inscription
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_TO_VALIDATE]: [
        {
          icon: (
            <span title="Editer le dossier">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
            ),
        },
        {
          icon: (
            <span title="Voir les fichiers">
              <FileText className="w-5 h-5 text-cyan-500 hover:text-cyan-700" />
            </span>
          ),
          onClick: () => openFilesModal(row),
        },
        {
          icon: (
            <span title="Valider le dossier">
              <CheckCircle className="w-5 h-5 text-primary hover:text-secondary" />
            </span>
          ),
          onClick: () => {
            const url = `${FE_ADMIN_SUBSCRIPTIONS_VALIDATE_URL}?studentId=${row.student.id}&firstName=${row.student.first_name}&lastName=${row.student.last_name}&email=${row.student.guardians[0].associated_profile_email}&level=${row.student.level}&sepa_file=${row.sepa_file}&student_file=${row.registration_file}`;
            router.push(`${url}`);
          },
        },
        {
          icon: (
            <span title="Refuser le dossier">
              <XCircle className="w-5 h-5 text-red-500 hover:text-red-700" />
            </span>
          ),
          onClick: () => openRefusePopup(row),
        },
      ],
      // Etat "A relancer" - NON TESTE
      [RegistrationFormStatus.STATUS_TO_FOLLOW_UP]: [
        // To do...
      ],
      // Etat "Validé" :
      // - Editer le formulaire d'inscription
      // - Visualiser les documents signés par les parents
      // - A ajouter : Action pour éditer le suivi de l'élève
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_VALIDATED]: [
        {
          icon: (
            <span title="Editer le dossier">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
            ),
        },
        {
          icon: (
            <span title="Voir les fichiers">
              <FileText className="w-5 h-5 text-cyan-500 hover:text-cyan-700" />
            </span>
          ),
          onClick: () => openFilesModal(row),
        },
      ],
      // Etat "Archivé"
      // - Editer le formulaire d'inscription en lecture seule
      [RegistrationFormStatus.STATUS_ARCHIVED]: [
        {
          icon: (
            <span title="Editer le dossier">
              <Eye className="w-5 h-5 text-purple-500 hover:text-purple-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=false`
            ),
        },
      ],
      // Etat "En attente de signature de SEPA" :
      // - Editer le formulaire d'inscription
      // - Visualiser les documents signés par les parents
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_SEPA_PENDING]: [
        {
          icon: (
            <span title="Editer le dossier">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
            ),
        },
        {
          icon: (
            <span title="Voir les fichiers">
              <FileText className="w-5 h-5 text-cyan-500 hover:text-cyan-700" />
            </span>
          ),
          onClick: () => openFilesModal(row),
        },
      ],
      // Etat "SEPA à envoyer" :
      // - Editer le formulaire d'inscription
      // - Visualiser les documents signés par les parents
      // - Envoyer le mandat SEPA aux parents
      // - Archiver le dossier
      [RegistrationFormStatus.STATUS_SEPA_TO_SEND]: [
        {
          icon: (
            <span title="Editer le dossier">
              <Edit className="w-5 h-5 text-blue-500 hover:text-blue-700" />
            </span>
          ),
          onClick: () =>
            router.push(
              `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
            ),
        },
        {
          icon: (
            <span title="Voir les fichiers">
              <FileText className="w-5 h-5 text-cyan-500 hover:text-cyan-700" />
            </span>
          ),
          onClick: () => openFilesModal(row),
        },
        {
          icon: (
            <span title="Uploader un mandat SEPA">
              <Upload className="w-5 h-5 text-primary hover:text-secondary" />
            </span>
          ),
          onClick: () => openSepaUploadModal(row),
        },
      ],
      default: [
        {
          icon: (
            <span title="Archiver le dossier">
              <Archive className="w-5 h-5 text-red-500 hover:text-red-700" />
            </span>
          ),
          onClick: () =>
            archiveFicheInscription(
              row.student.id,
              row.student.last_name,
              row.student.first_name
            ),
        },
      ],
    };

    // Combine actions for the specific status and default actions
    return [
      ...(actions[row.status] || []),
      ...(row.status !== 6 ? actions.default : []),
    ];
  };

  const columns = [
    {
      name: t('photo'),
      transform: (row) => (
        <div className="flex justify-center items-center">
          {row.student.photo ? (
            <a
              href={getSecureFileUrl(row.student.photo)} // Lien vers la photo
              target="_blank"
              rel="noopener noreferrer"
            >
              <img
                src={getSecureFileUrl(row.student.photo)}
                alt={`${row.student.first_name} ${row.student.last_name}`}
                className="w-10 h-10 object-cover transition-transform duration-200 hover:scale-125 cursor-pointer rounded-full"
              />
            </a>
          ) : (
            <div className="w-10 h-10 flex items-center justify-center bg-gray-200 rounded-full">
              <span className="text-gray-500 text-sm font-semibold">
                {row.student.first_name[0]}
                {row.student.last_name[0]}
              </span>
            </div>
          )}
        </div>
      ),
    },
    { name: t('studentName'), transform: (row) => row.student.last_name },
    { name: t('studentFistName'), transform: (row) => row.student.first_name },
    {
      name: t('mainContactMail'),
      transform: (row) =>
        row.student.guardians &&
        row.student.guardians.length > 0 &&
        row.student.guardians[0].associated_profile_email,
    },
    {
      name: t('phone'),
      transform: (row) =>
        row.student.guardians[0]?.phone ? (
          <PhoneLabel phoneNumber={row.student.guardians[0]?.phone} />
        ) : null, // N'affiche rien si le numéro de téléphone est absent
    },
    {
      name: t('lastUpdateDate'),
      transform: (row) => row.formatted_last_update,
    },
    {
      name: t('registrationFileStatus'),
      transform: (row) => (
        <div className="flex justify-center items-center h-full">
          <StatusLabel
            status={row.status}
            onChange={(newStatus) =>
              updateStatusAction(row.student.id, newStatus)
            }
            showDropdown={false}
          />
        </div>
      ),
    },
    {
      name: 'Actions',
      transform: (row) => (
        <div className="flex justify-center space-x-2">
          {getActionsByStatus(row).map((action, index) => (
            <button
              key={index}
              onClick={action.onClick}
              className="p-2 rounded-full hover:bg-gray-100 transition"
            >
              {action.icon}
            </button>
          ))}
        </div>
      ),
    },
  ];

  const getEmptyMessageForTab = (tabFilter) => {
    if (searchTerm !== '') {
      return (
        <EmptyState
          icon={Search}
          title="Aucun dossier trouvé"
          description="Modifiez votre recherche pour trouver un dossier d'inscription."
        />
      );
    }
    if (tabFilter === CURRENT_YEAR_FILTER) {
      return (
        <EmptyState
          icon={FileText}
          title="Aucun dossier d'inscription pour l'année en cours"
          description="Commencez par créer un dossier d'inscription pour l'année scolaire en cours."
          actionLabel="Créer un dossier"
          actionIcon={Plus}
          onAction={() => router.push(FE_ADMIN_SUBSCRIPTIONS_CREATE_URL)}
        />
      );
    }
    if (tabFilter === NEXT_YEAR_FILTER) {
      return (
        <EmptyState
          icon={FileText}
          title="Aucun dossier pour l'année prochaine"
          description="Aucun dossier n'a encore été créé pour la prochaine année scolaire."
          actionLabel="Créer un dossier"
          actionIcon={Plus}
          onAction={() => router.push(FE_ADMIN_SUBSCRIPTIONS_CREATE_URL)}
        />
      );
    }
    return (
      <EmptyState
        icon={Archive}
        title="Aucun dossier archivé"
        description="Aucun dossier archivé n'est disponible pour les années précédentes."
      />
    );
  };

  const renderTabContent = (data, currentPage, totalPages, tabFilter) => (
    <div className="p-4">
      <div className="flex justify-between items-center mb-4 w-full">
        <div className="relative flex-grow">
          <Search
            className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
            size={20}
          />
          <input
            type="text"
            placeholder={t('searchStudent')}
            className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md"
            value={searchTerm}
            onChange={handleSearchChange}
          />
        </div>
        <div className="flex items-center gap-2 ml-4">
          <button
            onClick={handleExportCSV}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-secondary bg-primary/10 rounded hover:bg-primary/20 transition-colors"
            title="Exporter en CSV"
          >
            <Download className="w-4 h-4" />
            Exporter
          </button>
          {profileRole !== 0 && (
            <button
              onClick={() => router.push(FE_ADMIN_SUBSCRIPTIONS_CREATE_URL)}
              className="flex items-center bg-primary text-white p-2 rounded-full shadow hover:bg-secondary transition duration-200"
            >
              <Plus className="w-5 h-5" />
            </button>
          )}
        </div>
      </div>
      <DjangoCSRFToken csrfToken={csrfToken} />
      <Table
        key={`${tabFilter}-${currentPage}-${searchTerm}`}
        data={data}
        columns={columns}
        itemsPerPage={itemsPerPage}
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={handlePageChange}
        emptyMessage={getEmptyMessageForTab(tabFilter)}
      />
    </div>
  );

  if (isLoading) {
    return <Loader />;
  }

  return (
    <div className="h-full flex flex-col">
      <SidebarTabs
        tabs={[
          {
            id: CURRENT_YEAR_FILTER,
            label: `${currentSchoolYear}${totalCurrentYear > 0 ? ` (${totalCurrentYear})` : ''}`,
            content: renderTabContent(
              registrationFormsDataCurrentYear,
              currentSchoolYearPage,
              totalCurrentSchoolYearPages,
              CURRENT_YEAR_FILTER
            ),
          },
          {
            id: NEXT_YEAR_FILTER,
            label: `${nextSchoolYear}${totalNextYear > 0 ? ` (${totalNextYear})` : ''}`,
            content: renderTabContent(
              registrationFormsDataNextYear,
              currentSchoolNextYearPage,
              totalNextSchoolYearPages,
              NEXT_YEAR_FILTER
            ),
          },
          {
            id: HISTORICAL_FILTER,
            label: `${t('historical')}${totalHistorical > 0 ? ` (${totalHistorical})` : ''}`,
            content: renderTabContent(
              registrationFormsDataHistorical,
              currentSchoolHistoricalYearPage,
              totalHistoricalPages,
              HISTORICAL_FILTER
            ),
          },
        ]}
        onTabChange={(newTab) => setActiveTab(newTab)}
      />
      <Popup
        isOpen={confirmPopupVisible}
        message={confirmPopupMessage}
        onConfirm={confirmPopupOnConfirm}
        onCancel={() => setConfirmPopupVisible(false)}
      />

      {/* Popup de refus de dossier */}
      <Popup
        isOpen={isRefusePopupOpen}
        message={
          <div>
            <div className="mb-2 font-semibold">
              Veuillez indiquer la raison du refus :
            </div>
            <Textarea
              value={refuseReason}
              onChange={(e) => setRefuseReason(e.target.value)}
              placeholder="Ex : Réception de dossier trop tardive"
              rows={3}
              className="w-full"
            />
          </div>
        }
        onConfirm={handleRefuse}
        onCancel={() => setIsRefusePopupOpen(false)}
      />

      {isSepaUploadModalOpen && (
        <Modal
          isOpen={isSepaUploadModalOpen}
          setIsOpen={setIsSepaUploadModalOpen}
          title="Uploader un mandat SEPA"
        >
          <FileUpload
            selectionMessage="Sélectionnez un mandat SEPA à uploader"
            onFileSelect={(file) =>
              handleSepaFileUpload(file, selectedRowForUpload)
            }
          />
        </Modal>
      )}
      {isFilesModalOpen && (
        <FilesModal
          isOpen={isFilesModalOpen}
          setIsOpen={setIsFilesModalOpen}
          selectedRegisterForm={selectedRegisterForm}
        />
      )}
    </div>
  );
}
