// Import des dépendances nécessaires
import React, { useState, useEffect } from 'react';
import InputText from '@/components/InputText';
import SelectChoice from '@/components/SelectChoice';
import ResponsableInputFields from '@/components/Inscription/ResponsableInputFields';
import Loader from '@/components/Loader';
import Button from '@/components/Button';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import Table from '@/components/Table';
import { fetchRegisterForm, fetchTemplatesFromRegistrationFiles } from '@/app/actions/subscriptionAction';
import { fetchRegistrationFileFromGroup, 
            fetchRegistrationTemplateMaster, 
            downloadTemplate, 
            createRegistrationTemplates, 
            editRegistrationTemplates, 
            deleteRegistrationTemplates 
        } from '@/app/actions/registerFileGroupAction';
import { Download, Upload, Trash2, Eye } from 'lucide-react';
import { BASE_URL } from '@/utils/Url';
import DraggableFileUpload from '@/components/DraggableFileUpload';
import Modal from '@/components/Modal';
import FileStatusLabel from '@/components/FileStatusLabel';
import logger from '@/utils/logger';
import StudentInfoForm from '@/components/Inscription/StudentInfoForm';
import FilesToSign from '@/components/Inscription/FilesToSign';
import FilesToUpload from '@/components/Inscription/FilesToUpload';
import { DocusealForm } from '@docuseal/react';
import { ESTABLISHMENT_ID } from '@/utils/Url';

/**
 * Composant de formulaire d'inscription partagé
 * @param {string} studentId - ID de l'étudiant
 * @param {string} csrfToken - Token CSRF pour la sécurité
 * @param {function} onSubmit - Fonction de soumission du formulaire
 * @param {string} cancelUrl - URL de redirection en cas d'annulation
 * @param {object} errors - Erreurs de validation du formulaire
 */
export default function InscriptionFormShared({
    studentId,
    csrfToken,
    onSubmit,
    cancelUrl,
    errors = {} // Nouvelle prop pour les erreurs
}) {
    // États pour gérer les données du formulaire
    const [isLoading, setIsLoading] = useState(true);
    const [formData, setFormData] = useState({
        id: '',
        last_name: '',
        first_name: '',
        address: '',
        birth_date: '',
        birth_place: '',
        birth_postal_code: '',
        nationality: '',
        attending_physician: '',
        level: ''
    });

    const [guardians, setGuardians] = useState([]);

    // États pour la gestion des fichiers
    const [uploadedFiles, setUploadedFiles] = useState([]);
    const [fileTemplates, setFileTemplates] = useState([]);
    const [fileGroup, setFileGroup] = useState(null);
    const [fileName, setFileName] = useState("");
    const [file, setFile] = useState("");
    const [showUploadModal, setShowUploadModal] = useState(false);
    const [currentTemplateId, setCurrentTemplateId] = useState(null);

    const [currentPage, setCurrentPage] = useState(1);

    // Chargement initial des données
    // Mettre à jour les données quand initialData change
    useEffect(() => {
        if (studentId) {
            fetchRegisterForm(studentId).then((data) => {
                logger.debug(data);

             setFormData({
                    id: data?.student?.id || '',
                    last_name: data?.student?.last_name || '',
                    first_name: data?.student?.first_name || '',
                    address: data?.student?.address || '',
                    birth_date: data?.student?.birth_date || '',
                    birth_place: data?.student?.birth_place || '',
                    birth_postal_code: data?.student?.birth_postal_code || '',
                    nationality: data?.student?.nationality || '',
                    attending_physician: data?.student?.attending_physician || '',
                    level: data?.student?.level || ''
                });
                setGuardians(data?.student?.guardians || []);
                setUploadedFiles(data.registration_files || []);
            });

            setIsLoading(false);
        }
    }, [studentId]);

    useEffect(() => {
        fetchTemplatesFromRegistrationFiles(studentId).then((data) => {
            setFileTemplates(data);
        })
    }, []);

    // Fonctions de gestion du formulaire et des fichiers
    const updateFormField = (field, value) => {
        setFormData(prev => ({...prev, [field]: value}));
    };

    // Gestion du téléversement de fichiers
    const handleFileUpload = async (file, fileName) => {
        if (!file || !currentTemplateId || !formData.id) {
            logger.error('Missing required data for upload');
            return;
        }

        const data = new FormData();
        data.append('file', file);
        data.append('name', fileName);
        data.append('template', currentTemplateId);
        data.append('register_form', formData.id);

        try {
            const response = await createRegistrationTemplates(data, csrfToken);
            if (response) {
                setUploadedFiles(prev => {
                    const newFiles = prev.filter(f => parseInt(f.template) !== currentTemplateId);
                    return [...newFiles, {
                        name: fileName,
                        template: currentTemplateId,
                        file: response.file
                    }];
                });

                // Rafraîchir les données du formulaire pour avoir les fichiers à jour
                if (studentId) {
                    fetchRegisterForm(studentId).then((data) => {
                        setUploadedFiles(data.registration_files || []);
                    });
                }
            }
        } catch (error) {
            logger.error('Error uploading file:', error);
        }
    };

    // Vérification si un fichier est déjà uploadé
    const isFileUploaded = (templateId) => {
        return uploadedFiles.find(template =>
            template.template === templateId
        );
    };

    // Récupération d'un fichier uploadé
    const getUploadedFile = (templateId) => {
        return uploadedFiles.find(file => parseInt(file.template) === templateId);
    };

    // Suppression d'un fichier
    const handleDeleteFile = async (templateId) => {
        const fileToDelete = getUploadedFile(templateId);
        if (!fileToDelete) return;

        try {
            await deleteRegistrationTemplates(fileToDelete.id, csrfToken);
            setUploadedFiles(prev => prev.filter(f => parseInt(f.template) !== templateId));
        } catch (error) {
            logger.error('Error deleting file:', error);
        }
    };

    // Soumission du formulaire
    const handleSubmit = (e) => {
        e.preventDefault();
        const data ={
            student: {
                ...formData,
                guardians
            },
            establishment: ESTABLISHMENT_ID,
            status:3
        }
        onSubmit(data);
    };

    // Récupération des messages d'erreur
    const getError = (field) => {
        return errors?.student?.[field]?.[0];
    };

    const handleNextPage = () => {
        setCurrentPage(currentPage + 1);
    };
    
    const handlePreviousPage = () => {
        setCurrentPage(currentPage - 1);
    };

    const requiredFileTemplates = fileTemplates;

    // Configuration des colonnes pour le tableau des fichiers
    const columns = [
        { name: 'Nom du fichier', transform: (row) => row.name },
        { name: 'Fichier à Remplir', transform: (row) => row.is_required ? 'Oui' : 'Non' },
        { name: 'Fichier de référence', transform: (row) =>  row.file && <div className="flex items-center justify-center gap-2"> <a href={`${BASE_URL}${row.file}`} target='_blank' className="text-blue-500 hover:text-blue-700">
                    <Download size={16} />
                </a> </div>},
        { name: 'Statut', transform: (row) =>
            row.is_required && (
                <FileStatusLabel
                    status={isFileUploaded(row.id) ? 'sent' : 'pending'}
                />
            )
        },
        { name: 'Actions', transform: (row) => {
            if (!row.is_required) return null;

            const uploadedFile = getUploadedFile(row.id);

            if (uploadedFile) {
                return (
                    <div className="flex items-center justify-center gap-2">
                        <a
                            href={`${BASE_URL}${uploadedFile.file}`}
                            target="_blank"
                            className="text-blue-500 hover:text-blue-700"
                        >
                            <Eye size={16} />
                        </a>
                        <button
                            className="text-red-500 hover:text-red-700"
                            onClick={() => handleDeleteFile(row.id)}
                            type="button"
                        >
                            <Trash2 size={16} />
                        </button>
                    </div>
                );
            }

            return (
                <button
                    className="text-emerald-500 hover:text-emerald-700"
                    type="button"
                    onClick={() => {
                        setCurrentTemplateId(row.id);
                        setShowUploadModal(true);
                    }}
                >
                    <Upload size={16} />
                </button>
            );
        }},
    ];

    // Affichage du loader pendant le chargement
    if (isLoading) return <Loader />;

    // Rendu du composant
    return (
        <div className="max-w-4xl mx-auto p-6">
            <form onSubmit={handleSubmit} className="space-y-8">
                <DjangoCSRFToken  csrfToken={csrfToken}/>
                {/* Page 1 : Informations de l'élève et Responsables */}
                {currentPage === 1 && (
                    <StudentInfoForm
                        formData={formData}
                        updateFormField={updateFormField}
                        guardians={guardians}
                        setGuardians={setGuardians}
                        errors={errors}
                    />
                )}

                {/* Pages suivantes : Section Fichiers d'inscription */}
                {currentPage > 1 && currentPage <= requiredFileTemplates.length + 1 && (
                    <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
                        <h2 className="text-xl font-bold mb-4 text-gray-800">{requiredFileTemplates[currentPage - 2].name}</h2>
                        <DocusealForm
                            id="docusealForm"
                            src={"https://docuseal.com/s/"+requiredFileTemplates[currentPage - 2].slug}
                            withDownloadButton={false}
                            onComplete={() => {
                                downloadTemplate(requiredFileTemplates[currentPage - 2].slug)
                                    .then((data) => fetch(data))
                                    .then((response) => response.blob())
                                    .then((blob) => {
                                        const file = new File([blob], `${requiredFileTemplates[currentPage - 2].name}.pdf`, { type: blob.type });
                                        const updateData = new FormData();
                                        updateData.append('file', file);
                            
                                        return editRegistrationTemplates(requiredFileTemplates[currentPage - 2].id, updateData, csrfToken);
                                    })
                                    .then((data) => {
                                        logger.debug("EDIT TEMPLATE : ", data);
                                    })
                                    .catch((error) => {
                                        logger.error("error editing template : ", error);
                                    });
                            }}
                        >
                        </DocusealForm>
                    </div>
                )}

                {/* Dernière page : Section Fichiers parents */}
                {currentPage === requiredFileTemplates.length + 2 && (
                    <>
                        <FilesToUpload
                            fileTemplates={fileTemplates.filter(template => !template.is_required)}
                            columns={columns}
                        />
                    </>
                )}

                {/* Boutons de contrôle */}
                <div className="flex justify-end space-x-4">
                    {currentPage > 1 && (
                        <Button text="Précédent" onClick={(e) => { e.preventDefault(); handlePreviousPage(); }} />
                    )}
                    {currentPage < requiredFileTemplates.length + 2 && (
                        <Button text="Suivant" onClick={(e) => { e.preventDefault(); handleNextPage(); }} />
                    )}
                    {currentPage === requiredFileTemplates.length + 2 && (
                        <Button type="submit" text="Valider" primary />
                    )}
                </div>
            </form>
            {fileTemplates.length > 0 && (
                <Modal
                    isOpen={showUploadModal}
                    setIsOpen={setShowUploadModal}
                    title="Téléverser un fichier"
                    ContentComponent={() => (
                        <>
                            <DraggableFileUpload
                                className="w-full"
                                fileName={fileName}
                                onFileSelect={(selectedFile) => {
                                    if (selectedFile) {
                                        setFile(selectedFile);
                                        setFileName(selectedFile.name);
                                    }
                                }}
                            />
                            <div className="mt-4 flex justify-center space-x-4">
                                <Button
                                    text="Annuler"
                                    onClick={() => {
                                        setShowUploadModal(false);
                                        setCurrentTemplateId(null);
                                        setFile(null);
                                        setFileName("");
                                    }}
                                />
                                <Button
                                    text="Valider"
                                    onClick={() => {
                                        if (file && fileName) {
                                            handleFileUpload(file, fileName);
                                            setShowUploadModal(false);
                                            setCurrentTemplateId(null);
                                            setFile(null);
                                            setFileName("");
                                        }
                                    }}
                                    primary={true}
                                    disabled={!file || !fileName}
                                />
                            </div>
                        </>
                    )}
                />
            )}
        </div>
    );
}