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,
} from '@/utils/Url';

import { CURRENT_YEAR_FILTER } from '@/utils/constants';
import { errorHandler, requestResponseHandler } from './actionsHandlers';

export const editStudentCompetencies = (data, csrfToken) => {
  const request = new Request(`${BE_SUBSCRIPTION_STUDENT_COMPETENCIES_URL}`, {
    method: 'PUT',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

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}`;

  const request = new Request(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

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 fetch(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const fetchRegisterForm = (id) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`) // Utilisation de studentId au lieu de codeDI
    .then(requestResponseHandler)
    .catch(errorHandler);
};
export const fetchLastGuardian = () => {
  return fetch(`${BE_SUBSCRIPTION_LAST_GUARDIAN_ID_URL}`)
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const editRegisterForm = (id, data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, {
    method: 'PUT',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    body: data,
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const createRegisterForm = (data, csrfToken) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}`;
  return fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    body: JSON.stringify(data),
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const sendRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/send`;
  return fetch(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const resendRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/resend`;
  return fetch(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};
export const archiveRegisterForm = (id) => {
  const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/archive`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const searchStudents = (establishmentId, query) => {
  const url = `${BE_SUBSCRIPTION_SEARCH_STUDENTS_URL}/?establishment_id=${establishmentId}&q=${encodeURIComponent(query)}`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const fetchStudents = (establishment, id = null, status = 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}`;
    }
  }
  const request = new Request(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

export const fetchChildren = (id, establishment) => {
  const request = new Request(
    `${BE_SUBSCRIPTION_CHILDRENS_URL}/${id}?establishment_id=${establishment}`,
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

export async function getRegisterFormFileTemplate(fileId) {
  const response = await fetch(
    `${BE_SUBSCRIPTION_REGISTERFORM_FILE_TEMPLATE_URL}/${fileId}`,
    {
      credentials: 'include',
      headers: {
        Accept: 'application/json',
      },
    }
  );
  if (!response.ok) {
    throw new Error('Failed to fetch file template');
  }
  return response.json();
}

export const fetchSchoolFileTemplatesFromRegistrationFiles = async (id) => {
  const response = await fetch(
    `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/school_file_templates`,
    {
      credentials: 'include',
      headers: {
        Accept: 'application/json',
      },
    }
  );
  if (!response.ok) {
    throw new Error(
      'Erreur lors de la récupération des fichiers associés au groupe'
    );
  }
  return response.json();
};

export const fetchParentFileTemplatesFromRegistrationFiles = async (id) => {
  const response = await fetch(
    `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/parent_file_templates`,
    {
      credentials: 'include',
      headers: {
        Accept: 'application/json',
      },
    }
  );
  if (!response.ok) {
    throw new Error(
      'Erreur lors de la récupération des fichiers associés au groupe'
    );
  }
  return response.json();
};

export const dissociateGuardian = async (studentId, guardianId) => {
  const response = await fetch(
    `${BE_SUBSCRIPTION_STUDENTS_URL}/${studentId}/guardians/${guardianId}/dissociate`,
    {
      credentials: 'include',
      method: 'PUT',
      headers: {
        Accept: 'application/json',
      },
    }
  );

  if (!response.ok) {
    // Extraire le message d'erreur du backend
    const errorData = await response.json();
    const errorMessage =
      errorData?.error || 'Une erreur est survenue lors de la dissociation.';

    // Jeter une erreur avec le message spécifique
    throw new Error(errorMessage);
  }

  return response.json();
};

export const fetchAbsences = (establishment) => {
  return fetch(
    `${BE_SUBSCRIPTION_ABSENCES_URL}?establishment_id=${establishment}`
  )
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const createAbsences = (data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_ABSENCES_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const editAbsences = (absenceId, payload, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_ABSENCES_URL}/${absenceId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    body: JSON.stringify(payload), // Sérialisez les données en JSON
    credentials: 'include',
  }).then((response) => {
    if (!response.ok) {
      return response.json().then((error) => {
        throw new Error(error);
      });
    }
    return response.json();
  });
};

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