'use client'
import React, { useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import InscriptionFormShared from '@/components/Inscription/InscriptionFormShared';
import { FE_ADMIN_SUBSCRIPTIONS_URL } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext';
import { editRegisterForm } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
const useFakeData = process.env.NEXT_PUBLIC_USE_FAKE_DATA === 'true';

export default function Page() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const idProfil = searchParams.get('id');
    const studentId = searchParams.get('studentId');  // Changé de codeDI à studentId

    const [initialData, setInitialData] = useState(null);

    const [formErrors, setFormErrors] = useState({});
    const csrfToken = useCsrfToken();


    const handleSubmit = (data) => {
        if (useFakeData) {
            logger.debug('Fake submit:', data);
            return;
        }

        editRegisterForm(studentId, data, csrfToken)

        .then((result) => {
            logger.debug('Success:', result);
            router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
        })
        .catch((error) => {
            logger.error('Error:', error.message);
            if (error.details) {
                logger.error('Form errors:', error.details);
                setFormErrors(error.details);
            }
        });

    };

    return (
        <InscriptionFormShared
            studentId={studentId}
            csrfToken={csrfToken}
            onSubmit={handleSubmit}
            cancelUrl={FE_ADMIN_SUBSCRIPTIONS_URL}
            errors={formErrors}
        />
    );
}