import React, { useState, useEffect } from 'react';
import {
  fetchRegistrationFileGroups,
  createRegistrationSchoolFileTemplate,
  cloneTemplate,
  generateToken,
} from '@/app/actions/registerFileGroupAction';
import { DocusealBuilder } from '@docuseal/react';
import logger from '@/utils/logger';
import MultiSelect from '@/components/MultiSelect'; // Import du composant MultiSelect
import { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext';
import Popup from '@/components/Popup';

export default function FileUploadDocuSeal({
  handleCreateTemplateMaster,
  handleEditTemplateMaster,
  fileToEdit = null,
  onSuccess,
}) {
  const [groups, setGroups] = useState([]);
  const [token, setToken] = useState(null);
  const [templateMaster, setTemplateMaster] = useState(null);
  const [uploadedFileName, setUploadedFileName] = useState('');
  const [selectedGroups, setSelectedGroups] = useState([]);
  const [guardianDetails, setGuardianDetails] = useState([]);

  const [popupVisible, setPopupVisible] = useState(false);
  const [popupMessage, setPopupMessage] = useState('');

  const csrfToken = useCsrfToken();

  const { selectedEstablishmentId } = useEstablishment();

  useEffect(() => {
    fetchRegistrationFileGroups(selectedEstablishmentId).then((data) =>
      setGroups(data)
    );

    if (fileToEdit) {
      setUploadedFileName(fileToEdit.name || '');
      setSelectedGroups(fileToEdit.groups || []);
    }
  }, [fileToEdit]);

  useEffect(() => {
    const email = 'n3wt.school@gmail.com';
    const id = fileToEdit ? fileToEdit.id : null;

    generateToken(email, id)
      .then((data) => {
        setToken(data.token);
      })
      .catch((error) =>
        console.error('Erreur lors de la génération du token:', error)
      );
  }, [fileToEdit]);

  const handleGroupChange = (selectedGroups) => {
    setSelectedGroups(selectedGroups);

    const details = selectedGroups.flatMap((group) =>
      group.registration_forms.flatMap((form) =>
        form.guardians.map((guardian) => ({
          email: guardian.associated_profile_email,
          last_name: form.last_name,
          first_name: form.first_name,
          registration_form: form.student_id,
        }))
      )
    );
    setGuardianDetails(details); // Mettre à jour la variable d'état avec les détails des guardians
  };

  const handleLoad = (detail) => {
    logger.debug('loading template id : ', detail);
    setTemplateMaster(detail);
  };

  const handleUpload = (detail) => {
    logger.debug('Uploaded file detail:', detail);
    setUploadedFileName(detail.name);
  };

  const handleChange = (detail) => {
    logger.debug(detail);
    setUploadedFileName(detail.name);
  };

  const handleSubmit = (data) => {
    // Vérifier si au moins un champ a la propriété "required" à true
    const hasRequiredField = data.fields.some(
      (field) => field.required === true
    );

    if (!hasRequiredField) {
      setPopupMessage('Veuillez définir au moins un champ comme requis.');
      setPopupVisible(true);
      return;
    }

    const is_required = data.fields.length > 0;
    if (fileToEdit) {
      logger.debug('Modification du template master:', templateMaster?.id);
      handleEditTemplateMaster({
        name: uploadedFileName,
        group_ids: selectedGroups.map((group) => group.id),
        id: templateMaster?.id,
        is_required: is_required,
      });
    } else {
      logger.debug('Création du template master:', templateMaster?.id);
      handleCreateTemplateMaster({
        name: uploadedFileName,
        group_ids: selectedGroups.map((group) => group.id),
        id: templateMaster?.id,
        is_required: is_required,
      });

      guardianDetails.forEach((guardian, index) => {
        logger.debug('creation du clone avec required : ', is_required);
        cloneTemplate(templateMaster?.id, guardian.email, is_required)
          .then((clonedDocument) => {
            // Sauvegarde des schoolFileTemplates clonés dans la base de données
            const data = {
              name: `${uploadedFileName}_${guardian.first_name}_${guardian.last_name}`,
              slug: clonedDocument.slug,
              id: clonedDocument.id,
              master: templateMaster?.id,
              registration_form: guardian.registration_form,
            };
            console.log('creation : ', data);
            createRegistrationSchoolFileTemplate(data, csrfToken)
              .then((response) => {
                logger.debug('Template enregistré avec succès:', response);
                onSuccess();
              })
              .catch((error) => {
                logger.error(
                  "Erreur lors de l'enregistrement du template:",
                  error
                );
              });

            // Logique pour envoyer chaque template au submitter
            logger.debug('Sending template to:', guardian.email);
          })
          .catch((error) => {
            logger.error('Error during cloning or sending:', error);
          });
      });
    }
  };

  return (
    <div className="h-full flex flex-col mt-4 space-y-6">
      <Popup
        visible={popupVisible}
        message={popupMessage}
        onConfirm={() => setPopupVisible(false)}
        onCancel={() => setPopupVisible(false)}
        uniqueConfirmButton={true}
      />
      {/* Contenu principal */}
      <div className="grid grid-cols-10 gap-6 items-start">
        {/* Sélection des groupes */}
        <div className="col-span-2 bg-white p-4 rounded-lg shadow-md border border-gray-200">
          <h3 className="text-lg font-medium text-gray-800 mb-4">
            Dossiers d'inscription
          </h3>
          <MultiSelect
            name="groups"
            label="Sélection de dossier(s) d'inscription"
            options={groups}
            selectedOptions={selectedGroups}
            onChange={handleGroupChange}
            errorMsg={null}
          />
        </div>

        {/* Zone de configuration des documents */}
        <div className="col-span-8 bg-white p-6 rounded-lg shadow-md border border-gray-200">
          {selectedGroups.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-center space-y-4">
              {/* Icône circulaire modernisée */}
              <div className="bg-emerald-100 p-6 rounded-full flex items-center justify-center shadow-md">
                <div className="w-12 h-12 bg-emerald-200 rounded-full flex items-center justify-center">
                  <span className="text-emerald-600 font-bold text-2xl">+</span>
                </div>
              </div>

              {/* Message d'information */}
              <p className="text-gray-600 text-sm font-medium">
                Veuillez sélectionner au moins un groupe pour continuer.
              </p>
            </div>
          ) : (
            token && (
              <div className="h-full overflow-auto">
                <DocusealBuilder
                  token={token}
                  headers={{
                    Authorization: `Bearer ${token}`,
                  }}
                  withSendButton={false}
                  withSignYourselfButton={false}
                  autosave={false}
                  withDocumentsList={false}
                  language={'fr'}
                  onLoad={handleLoad}
                  onUpload={handleUpload}
                  onChange={handleChange}
                  onSave={handleSubmit}
                  className="h-full overflow-auto"
                  style={{ maxHeight: '65vh' }}
                />
              </div>
            )
          )}
        </div>
      </div>
    </div>
  );
}
