import {
  BE_SUBSCRIPTION_STUDENTS_URL,
  BE_SUBSCRIPTION_CHILDRENS_URL,
  BE_SUBSCRIPTION_REGISTERFORMS_URL,
  BE_SUBSCRIPTION_LAST_GUARDIAN_ID_URL,
  BE_SUBSCRIPTION_ABSENCES_URL,
  BE_SUBSCRIPTION_STUDENT_COMPETENCIES_URL,
  BE_SUBSCRIPTION_SEARCH_STUDENTS_URL,
  BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL,
  BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_TEMPLATES_URL,
} from '@/utils/Url';

import { CURRENT_YEAR_FILTER } from '@/utils/constants';
import { fetchWithAuth, fetchWithAuthRaw } from '@/utils/fetchWithAuth';
import logger from '@/utils/logger';

export const editStudentCompetencies = (data, csrfToken) => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_STUDENT_COMPETENCIES_URL}`, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

export const fetchStudentCompetencies = (id, period) => {
  // Si period est vide, ne pas l'ajouter à l'URL
  const url = period
    ? `${BE_SUBSCRIPTION_STUDENT_COMPETENCIES_URL}?student_id=${id}&period=${period}`
    : `${BE_SUBSCRIPTION_STUDENT_COMPETENCIES_URL}?student_id=${id}`;

  return fetchWithAuth(url);
};

export const fetchRegisterForms = (
  establishment,
  filter = CURRENT_YEAR_FILTER,
  page = '',
  pageSize = '',
  search = ''
) => {
  let url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}?filter=${filter}&establishment_id=${establishment}`;
  if (page !== '' && pageSize !== '') {
    url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}?filter=${filter}&establishment_id=${establishment}&page=${page}&search=${search}`;
  }
  return fetchWithAuth(url);
};

export const fetchRegisterForm = (id) => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`); // Utilisation de studentId au lieu de codeDI
};
export const fetchLastGuardian = () => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_LAST_GUARDIAN_ID_URL}`);
};

export const editRegisterForm = (id, data, csrfToken) => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: data,
  });
};

export const autoSaveRegisterForm = async (id, data, csrfToken) => {
  try {
    // Version allégée pour auto-save - ne pas envoyer tous les fichiers
    const autoSaveData = new FormData();

    // Ajouter seulement les données textuelles pour l'auto-save
    if (data.student) {
      autoSaveData.append('student_data', JSON.stringify(data.student));
    }
    if (data.guardians) {
      autoSaveData.append('guardians_data', JSON.stringify(data.guardians));
    }
    if (data.siblings) {
      autoSaveData.append('siblings_data', JSON.stringify(data.siblings));
    }
    if (data.currentPage) {
      autoSaveData.append('current_page', data.currentPage);
    }
    autoSaveData.append('auto_save', 'true');

    return fetchWithAuth(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, {
      method: 'PATCH', // Utiliser PATCH pour les mises à jour partielles
      headers: { 'X-CSRFToken': csrfToken },
      body: autoSaveData,
    })
      .then(() => {})
      .catch(() => {
        // Silent fail pour l'auto-save
        logger.debug('Auto-save failed silently');
      });
  } catch (error) {
    // Silent fail pour l'auto-save
    logger.debug('Auto-save error:', error);
  }
};

export const createRegisterForm = (data, csrfToken) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}`;
  return fetchWithAuth(url, {
    method: 'POST',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

export const sendRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/send`;
  return fetchWithAuth(url);
};

export const resendRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/resend`;
  return fetchWithAuth(url);
};
export const archiveRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/archive`;
  return fetchWithAuth(url);
};

export const searchStudents = (establishmentId, query) => {
  const url = `${BE_SUBSCRIPTION_SEARCH_STUDENTS_URL}/?establishment_id=${establishmentId}&q=${encodeURIComponent(query)}`;
  return fetchWithAuth(url);
};

export const fetchStudents = (establishment, id = null, status = null, schoolYear = null) => {
  let url;
  if (id) {
    url = `${BE_SUBSCRIPTION_STUDENTS_URL}/${id}`;
  } else {
    url = `${BE_SUBSCRIPTION_STUDENTS_URL}?establishment_id=${establishment}`;
    if (status) {
      url += `&status=${status}`;
    }
    if (schoolYear) {
      url += `&school_year=${encodeURIComponent(schoolYear)}`;
    }
  }
  return fetchWithAuth(url);
};

export const fetchChildren = (id, establishment) => {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_CHILDRENS_URL}/${id}?establishment_id=${establishment}`
  );
};

export async function getRegisterFormFileTemplate(fileId) {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_REGISTERFORM_FILE_TEMPLATE_URL}/${fileId}`
  );
}

export const fetchSchoolFileTemplatesFromRegistrationFiles = (id) => {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/school_file_templates`
  );
};

export const fetchParentFileTemplatesFromRegistrationFiles = (id) => {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/parent_file_templates`
  );
};

export const dissociateGuardian = (studentId, guardianId) => {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_STUDENTS_URL}/${studentId}/guardians/${guardianId}/dissociate`,
    {
      method: 'PUT',
    }
  );
};

export const fetchAbsences = (establishment) => {
  return fetchWithAuth(
    `${BE_SUBSCRIPTION_ABSENCES_URL}?establishment_id=${establishment}`
  );
};

export const createAbsences = (data, csrfToken) => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_ABSENCES_URL}`, {
    method: 'POST',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

export const editAbsences = (absenceId, payload, csrfToken) => {
  return fetchWithAuth(`${BE_SUBSCRIPTION_ABSENCES_URL}/${absenceId}`, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(payload),
  });
};

export const deleteAbsences = (id, csrfToken) => {
  return fetchWithAuthRaw(`${BE_SUBSCRIPTION_ABSENCES_URL}/${id}`, {
    method: 'DELETE',
    headers: { 'X-CSRFToken': csrfToken },
  });
};

/**
 * Récupère les formulaires maîtres d'inscription pour un établissement
 * @param {number} establishmentId - ID de l'établissement
 * @returns {Promise<Array>} Liste des formulaires
 */
export const fetchRegistrationSchoolFileMasters = (establishmentId) => {
  const url = `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}?establishment_id=${establishmentId}`;
  return fetchWithAuth(url);
};

/**
 * Sauvegarde les réponses d'un formulaire dans RegistrationSchoolFileTemplate
 * @param {number} templateId - ID du RegistrationSchoolFileTemplate
 * @param {Object} formTemplateData - Données du formulaire à sauvegarder
 * @param {string} csrfToken - Token CSRF
 * @returns {Promise} Résultat de la sauvegarde
 */
export const saveFormResponses = (templateId, formTemplateData, csrfToken) => {
  const url = `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_TEMPLATES_URL}/${templateId}`;
  const payload = {
    formTemplateData: formTemplateData,
  };
  return fetchWithAuth(url, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(payload),
  });
};

/**
 * Récupère les données sauvegardées d'un RegistrationSchoolFileTemplate
 * @param {number} templateId - ID du RegistrationSchoolFileTemplate
 * @returns {Promise<Object>} Template avec formTemplateData
 */
export const fetchFormResponses = (templateId) => {
  const url = `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_TEMPLATES_URL}/${templateId}`;
  return fetchWithAuth(url);
};
