import React, { useState, useEffect } from 'react';
import ToggleSwitch from '@/components/ToggleSwitch'; // Import du composant ToggleSwitch
import { fetchRegistrationFileGroups, createRegistrationTemplates, cloneTemplate } from '@/app/actions/registerFileGroupAction';
import { DocusealBuilder } from '@docuseal/react';
import logger from '@/utils/logger';
import { BE_DOCUSEAL_GET_JWT, BASE_URL } from '@/utils/Url';
import Button from '@/components/Button'; // Import du composant Button
import MultiSelect from '@/components/MultiSelect'; // Import du composant MultiSelect
import { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext';

export default function FileUpload({ handleCreateTemplateMaster, handleEditTemplateMaster, fileToEdit = null, onSuccess }) {
  const [isRequired, setIsRequired] = useState(false); // État pour le toggle isRequired
  const [order, setOrder] = useState(0);
  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 csrfToken = useCsrfToken();

  const { selectedEstablishmentId } = useEstablishment();

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

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

  useEffect(() => {
    const body = fileToEdit
      ? JSON.stringify({
          user_email: 'n3wt.school@gmail.com',
          id: fileToEdit.id
        })
      : JSON.stringify({
          user_email: 'n3wt.school@gmail.com'
        });
  
    fetch('/api/docuseal/generateToken', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: body,
    })
    .then((response) => response.json())
    .then((data) => {
      setToken(data.token);
    })
    .catch((error) => console.error(error));
  }, [fileToEdit]);

  const handleFileNameChange = (event) => {
    setUploadedFileName(event.target.value);
  };

  const handleGroupChange = (selectedGroups) => {
    setSelectedGroups(selectedGroups);
  
    const details = selectedGroups.flatMap(group => 
      group.registration_forms.flatMap(form => 
        form.guardians.map(guardian => ({
          email: guardian.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) => {
    const templateId = detail?.id;
    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) => {
    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 templates 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
            };
            createRegistrationTemplates(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-4">
      <div className="grid grid-cols-10 gap-4 items-start">
        <div className="col-span-2">
          <MultiSelect
            name="groups"
            label="Sélection de groupes de fichiers"
            options={groups}
            selectedOptions={selectedGroups}
            onChange={handleGroupChange}
            errorMsg={null}
          />
        </div>
        <div className="col-span-8">
          {token && (
            <DocusealBuilder 
              token={token} 
              headers={{
                'Authorization': `Bearer ${token}`
              }}
              withSendButton={false}
              withSaveButton={false}
              withSignYourselfButton={false}
              autosave={false}
              language={'fr'}
              onLoad={handleLoad}
              onUpload={handleUpload}
              onChange={handleChange}
              onSave={handleSubmit}
              className="h-full overflow-auto" // Ajouter overflow-auto pour permettre le défilement
              style={{ maxHeight: '70vh' }} // Limiter la hauteur maximale du composant
              // Il faut auter l'host correspondant (une fois passé en HTTPS)
              //host="docuseal:3001"
            />
          )}
        </div>
      </div>
    </div>
  );
}