'use client';
import React, { useState, useEffect } from 'react';
import ToggleSwitch from '@/components/ToggleSwitch';
import { BASE_URL } from '@/utils/Url';
import {
  fetchSchoolFileTemplatesFromRegistrationFiles,
  fetchParentFileTemplatesFromRegistrationFiles,
} from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
import { School, CheckCircle } from 'lucide-react';
import SectionHeader from '@/components/SectionHeader';

export default function ValidateSubscription({
  studentId,
  firstName,
  lastName,
  sepa_file,
  student_file,
  onAccept,
}) {
  const [schoolFileTemplates, setSchoolFileTemplates] = useState([]);
  const [parentFileTemplates, setParentFileTemplates] = useState([]);
  const [currentTemplateIndex, setCurrentTemplateIndex] = useState(0);
  const [mergeDocuments, setMergeDocuments] = useState(false);

  useEffect(() => {
    // Récupérer les fichiers schoolFileTemplates
    fetchSchoolFileTemplatesFromRegistrationFiles(studentId)
      .then((data) => {
        setSchoolFileTemplates(data);
        logger.debug('Fichiers schoolFileTemplates récupérés:', data);
      })
      .catch((error) =>
        logger.error(
          'Erreur lors de la récupération des schoolFileTemplates:',
          error
        )
      );

    // Récupérer les fichiers parentFileTemplates
    fetchParentFileTemplatesFromRegistrationFiles(studentId)
      .then((data) => {
        setParentFileTemplates(data);
        logger.debug('Fichiers parentFileTemplates récupérés:', data);
      })
      .catch((error) =>
        logger.error(
          'Erreur lors de la récupération des parentFileTemplates:',
          error
        )
      );
  }, [studentId]);

  const handleAccept = () => {
    const fusionParam = mergeDocuments ? 'true' : 'false';

    const data = {
      status: 5,
      fusionParam: fusionParam,
    };

    onAccept(data);
  };

  const handleToggleMergeDocuments = () => {
    // Inverser l'état de mergeDocuments
    setMergeDocuments((prevState) => !prevState);
  };

  const allTemplates = [
    { name: 'Fiche élève', file: student_file, type: 'main' },
    ...schoolFileTemplates.map((template) => ({
      name: template.name || 'Document scolaire',
      file: template.file,
      description: template.description,
    })),
    ...parentFileTemplates.map((template) => ({
      name: template.master_name || 'Document parent',
      file: template.file,
      description: template.description,
    })),
    ...(sepa_file
      ? [
          {
            name: 'Mandat SEPA',
            file: sepa_file,
            description: 'Mandat SEPA pour prélèvement automatique',
          },
        ]
      : []),
  ];

  return (
    <div className="mb-4 w-full mx-auto">
      {/* En-tête de la section */}
      <SectionHeader
        icon={School}
        title={`Validation du dossier de ${firstName} ${lastName}`}
        description={`Année scolaire ${new Date().getFullYear()}-${new Date().getFullYear() + 1}`}
      />

      {/* Contenu principal */}
      <div className="flex gap-8">
        {/* Liste des documents */}
        <div className="w-1/4 bg-gray-50 p-4 rounded-lg shadow-sm border border-gray-200">
          <h3 className="text-lg font-semibold text-gray-800 mb-4">
            Liste des documents
          </h3>
          <ul className="space-y-2">
            {allTemplates.map((template, index) => (
              <li
                key={index}
                className={`flex items-center cursor-pointer ${
                  index === currentTemplateIndex
                    ? 'text-blue-600 font-bold'
                    : template.file !== null
                      ? 'text-green-600'
                      : 'text-gray-600'
                }`}
                onClick={() => setCurrentTemplateIndex(index)} // Mettre à jour l'index du template actuel
              >
                <span className="mr-2">
                  {template.file !== null ? (
                    <CheckCircle className="w-5 h-5 text-green-600" />
                  ) : (
                    <Hourglass className="w-5 h-5 text-gray-600" />
                  )}
                </span>
                {template.name}
              </li>
            ))}
          </ul>

          {/* ToggleSwitch et bouton de validation */}
          <div className="mt-6 flex items-center justify-between">
            <ToggleSwitch
              label="Fusionner"
              checked={mergeDocuments}
              onChange={handleToggleMergeDocuments}
            />
            <button
              onClick={handleAccept}
              className="px-4 py-2 bg-emerald-500 text-white rounded-md shadow-sm hover:bg-emerald-600 transition-colors"
            >
              Valider
            </button>
          </div>
        </div>

        {/* Affichage du fichier actuel */}
        <div className="w-3/4">
          {currentTemplateIndex < allTemplates.length && (
            <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
              <h3 className="text-lg font-semibold text-gray-800 mb-4">
                {allTemplates[currentTemplateIndex].name || 'Document sans nom'}
              </h3>
              <p className="text-sm text-gray-500 mb-4">
                {allTemplates[currentTemplateIndex].description ||
                  'Aucune description disponible pour ce document.'}
              </p>

              <iframe
                src={`${BASE_URL}/${allTemplates[currentTemplateIndex].file}`}
                title={
                  allTemplates[currentTemplateIndex].type === 'main'
                    ? 'Document Principal'
                    : 'Document Viewer'
                }
                className="w-full"
                style={{
                  height: '75vh',
                  border: 'none',
                }}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
