import React, { useState, useEffect } from 'react';
import Modal from '@/components/Modal';
import { FileText } from 'lucide-react';
import {
  fetchSchoolFileTemplatesFromRegistrationFiles,
  fetchParentFileTemplatesFromRegistrationFiles,
} from '@/app/actions/subscriptionAction';
import { getSecureFileUrl } from '@/utils/fileUrl';
import logger from '@/utils/logger';

const FilesModal = ({
  isOpen,
  setIsOpen,
  title = 'Fichiers disponibles',
  selectedRegisterForm,
}) => {
  const [files, setFiles] = useState({
    registrationFile: null,
    fusionFile: null,
    schoolFiles: [],
    parentFiles: [],
    sepaFile: null,
  });

  useEffect(() => {
    if (!selectedRegisterForm?.student?.id) {
      logger.error('selectedRegisterForm.student.id est invalide ou manquant.');
      return;
    }

    let fetchedSchoolFiles = []; // Déclaré dans un scope plus large

    // Fetch school and parent files sequentially
    fetchSchoolFileTemplatesFromRegistrationFiles(
      selectedRegisterForm.student.id
    )
      .then((schoolFiles) => {
        if (!Array.isArray(schoolFiles)) {
          logger.error(
            'Les fichiers scolaires ne sont pas un tableau :',
            schoolFiles
          );
          return;
        }

        fetchedSchoolFiles = schoolFiles; // Assigner les fichiers scolaires

        // Fetch parent files after school files
        return fetchParentFileTemplatesFromRegistrationFiles(
          selectedRegisterForm.student.id
        );
      })
      .then((parentFiles) => {
        // Construct the categorized files list
        const categorizedFiles = {
          registrationFile: selectedRegisterForm.student?.id
            ? {
                name: 'Fiche élève',
                url: `/api/generate-pdf?studentId=${selectedRegisterForm.student.id}`,
              }
            : null,
          fusionFile: selectedRegisterForm.fusion_file
            ? {
                name: 'Documents fusionnés',
                url: getSecureFileUrl(selectedRegisterForm.fusion_file),
              }
            : null,
          schoolFiles: fetchedSchoolFiles.map((file) => ({
            name: file.name || 'Document scolaire',
            url:
              file.file_url || file.file
                ? getSecureFileUrl(file.file_url || file.file)
                : null,
          })),
          parentFiles: parentFiles.map((file) => ({
            name: file.master_name || 'Document parent',
            url:
              file.file_url || file.file
                ? getSecureFileUrl(file.file_url || file.file)
                : null,
          })),
          sepaFile: selectedRegisterForm.sepa_file
            ? {
                name: 'Mandat SEPA',
                url: getSecureFileUrl(selectedRegisterForm.sepa_file),
              }
            : null,
        };
        setFiles(categorizedFiles);
      })
      .catch((error) => {
        logger.error('Erreur lors de la récupération des fichiers :', error);
      });
  }, [selectedRegisterForm]);

  return (
    <Modal
      isOpen={isOpen}
      setIsOpen={setIsOpen}
      title={
        <span className="text-2xl font-bold text-gray-800 border-b pb-2 mb-4">
          {title}
        </span>
      }
    >
      <div className="space-y-6">
        {/* Section Fiche élève */}
        {files.registrationFile && (
          <div>
            <h3 className="font-headline text-lg font-semibold text-gray-800 mb-4">
              Fiche élève
            </h3>
            <div className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-gray-500" />
              <a
                href={files.registrationFile.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-500 hover:text-blue-700 underline"
              >
                {files.registrationFile.name}
              </a>
            </div>
          </div>
        )}

        {/* Section Documents fusionnés */}
        {files.fusionFile && (
          <div>
            <h3 className="font-headline text-lg font-semibold text-gray-800 mb-4">
              Documents fusionnés
            </h3>
            <div className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-gray-500" />
              <a
                href={files.fusionFile.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-500 hover:text-blue-700 underline"
              >
                {files.fusionFile.name}
              </a>
            </div>
          </div>
        )}

        <hr className="border-t border-gray-300" />

        {/* Section Fichiers École */}
        <div>
          <h3 className="font-headline text-lg font-semibold text-gray-800 mb-4">
            Formulaires de l&apos;établissement
          </h3>
          <ul className="space-y-2">
            {files.schoolFiles.length > 0 ? (
              files.schoolFiles.map((file, index) => (
                <li key={index} className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-gray-500" />
                  {file.url ? (
                    <a
                      href={file.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-500 hover:text-blue-700 underline"
                    >
                      {file.name}
                    </a>
                  ) : (
                    <span className="text-gray-400">
                      {file.name} (Non disponible)
                    </span>
                  )}
                </li>
              ))
            ) : (
              <p className="text-gray-500">
                Aucun fichier scolaire disponible.
              </p>
            )}
          </ul>
        </div>

        <hr className="border-t border-gray-300" />

        {/* Section Fichiers Parent */}
        <div>
          <h3 className="font-headline text-lg font-semibold text-gray-800 mb-4">
            Pièces fournies
          </h3>
          <ul className="space-y-2">
            {files.parentFiles.length > 0 ? (
              files.parentFiles.map((file, index) => (
                <li key={index} className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-gray-500" />
                  {file.url ? (
                    <a
                      href={file.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-500 hover:text-blue-700 underline"
                    >
                      {file.name}
                    </a>
                  ) : (
                    <span className="text-gray-400">
                      {file.name} (Non disponible)
                    </span>
                  )}
                </li>
              ))
            ) : (
              <p className="text-gray-500">Aucun fichier parent disponible.</p>
            )}
          </ul>
        </div>

        <hr className="border-t border-gray-300" />

        {/* Section Mandat SEPA */}
        <div>
          <h3 className="font-headline text-lg font-semibold text-gray-800 mb-4">
            Mandat SEPA
          </h3>
          {files.sepaFile ? (
            <div className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-gray-500" />
              <a
                href={files.sepaFile.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-500 hover:text-blue-700 underline"
              >
                {files.sepaFile.name}
              </a>
            </div>
          ) : (
            <p className="text-gray-500">Aucun mandat SEPA disponible.</p>
          )}
        </div>
      </div>
    </Modal>
  );
};

export default FilesModal;
