'use client';
import React, { useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import ValidateSubscription from '@/components/Inscription/ValidateSubscription';
import { editRegisterFormWithBinaryFile } from '@/app/actions/subscriptionAction';
import { useCsrfToken } from '@/context/CsrfContext';
import logger from '@/utils/logger';
import Loader from '@/components/Loader';
import { FE_ADMIN_SUBSCRIPTIONS_URL } from '@/utils/Url';

export default function Page() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  // Récupérer les paramètres de la requête
  const studentId = searchParams.get('studentId');
  const firstName = searchParams.get('firstName');
  const lastName = searchParams.get('lastName');
  const sepa_file = searchParams.get('sepa_file');
  const student_file = searchParams.get('student_file');

  const csrfToken = useCsrfToken();

  const handleAcceptRF = (data) => {
    const formData = new FormData();
    formData.append('data', JSON.stringify(data));

    setIsLoading(true);
    // Appeler l'API pour mettre à jour le RF
    editRegisterFormWithBinaryFile(studentId, formData, csrfToken)
      .then((response) => {
        logger.debug('RF mis à jour avec succès:', response);
        router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
        setIsLoading(false);
        // Logique supplémentaire après la mise à jour (par exemple, redirection ou notification)
      })
      .catch((error) => {
        setIsLoading(false);
        logger.error('Erreur lors de la mise à jour du RF:', error);
      });
  };

  if (isLoading) {
    return <Loader />;
  }

  return (
    <ValidateSubscription
      studentId={studentId}
      firstName={firstName}
      lastName={lastName}
      sepa_file={sepa_file}
      student_file={student_file}
      onAccept={handleAcceptRF}
    />
  );
}
