'use client';
import React, { useState } from 'react';
import InscriptionFormShared from '@/components/Inscription/InscriptionFormShared';
import { useSearchParams, useRouter } from 'next/navigation';
import { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext';
import { FE_PARENTS_HOME_URL } from '@/utils/Url';
import { editRegisterForm } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
import Loader from '@/components/Loader';
import { useNotification } from '@/context/NotificationContext';

export default function Page() {
  const searchParams = useSearchParams();
  const { showNotification } = useNotification();
  const studentId = searchParams.get('studentId');
  const enable = searchParams.get('enabled') === 'true';
  const router = useRouter();
  const csrfToken = useCsrfToken();
  const { selectedEstablishmentId } = useEstablishment();
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = (data) => {
    setIsLoading(true);
    editRegisterForm(studentId, data, csrfToken)
      .then((result) => {
        setIsLoading(false);
        logger.debug('Success:', result);
        showNotification(
          "Dossier d'inscription soumis avec succès",
          'success',
          'Succès'
        );
        router.push(FE_PARENTS_HOME_URL);
      })
      .catch((error) => {
        setIsLoading(false);
        showNotification(
          "Erreur lors de la soumission du dossier d'inscription",
          'error',
          'Erreur'
        );
        logger.error('Error:', error);
      });
  };

  if (isLoading === true) {
    return <Loader />; // Affichez le composant Loader
  }

  return (
    <InscriptionFormShared
      studentId={studentId}
      csrfToken={csrfToken}
      selectedEstablishmentId={selectedEstablishmentId}
      onSubmit={handleSubmit}
      cancelUrl={FE_PARENTS_HOME_URL}
      enable={enable}
    />
  );
}
