'use client';

import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { SnackbarProvider } from 'notistack';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import ThemeProvider from '@/shared/theme';
import CandidateFormComponent from '@/shared/components/candidate-form/candidate-form';

export default function CandidateFormPage() {
  const params = useParams();
  const [mounted, setMounted] = useState(false);
  const [token, setToken] = useState<string>('');

  // Ensure hydration on client side only
  useEffect(() => {
    setMounted(true);
    try {
      const raw = (params as any)?.token;
      const fromParams = Array.isArray(raw) ? raw[0] : (raw != null ? String(raw) : '');
      if (fromParams) {
        setToken(fromParams);
        return;
      }
    } catch {}
    if (typeof window !== 'undefined') {
      const parts = window.location.pathname.split('/');
      setToken(parts[parts.length - 1] || '');
    }
  }, [params]);

  // Prevent SSR mismatch by not rendering until mounted
  if (!mounted) {
    return null;
  }

  if (!token) {
    return (
      <div style={{ padding: '2rem', textAlign: 'center' }}>
        <h1>Token de formulaire manquant</h1>
        <p>Le lien semble être invalide. Veuillez vérifier votre URL.</p>
      </div>
    );
  }

  return (
    <ThemeProvider>
      <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
        <SnackbarProvider 
          maxSnack={3}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
        >
          <div style={{ 
            minHeight: '100vh', 
            backgroundColor: '#f5f5f5',
            backgroundImage: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            padding: '1rem 0'
          }}>
            <CandidateFormComponent token={token} />
          </div>
        </SnackbarProvider>
      </LocalizationProvider>
    </ThemeProvider>
  );
}