'use client';

import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Grid,
  Paper,
  Alert,
  CircularProgress,
  Divider,
  Container,
} from '@mui/material';
import { useRouter } from 'next/navigation';
import { candidateFormApi, CandidateForm, FormField } from '@/shared/api/endpoints/candidate-form';
import CandidateFormField from './candidate-form-field';
import { enqueueSnackbar } from 'notistack';

interface CandidateFormProps {
  token: string;
}

export default function CandidateFormComponent({ token }: CandidateFormProps) {
  const router = useRouter();
  const [form, setForm] = useState<CandidateForm | null>(null);
  const [responses, setResponses] = useState<Record<string, any>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);
  const [externalUrl, setExternalUrl] = useState<string | null>(null);

  // Ensure component is mounted on client side
  useEffect(() => {
    setMounted(true);
  }, []);

  // Load form data with AbortController to prevent multiple requests
  useEffect(() => {
    if (!token || !mounted) return;
    
    const abortController = new AbortController();
    let isCancelled = false;
    
    const loadForm = async () => {
      if (isCancelled) return;
      
      try {
        setLoading(true);
        setError(null);
        
        const formData = await candidateFormApi.getFormByToken(token, abortController.signal);
        
        if (isCancelled) return;
        
        setForm(formData);
        const maybeExternal = (formData as any)?.externalFormUrl as string | undefined;
        setExternalUrl(maybeExternal && typeof maybeExternal === 'string' && maybeExternal.length > 0 ? maybeExternal : null);
        
        // Check if form is expired or already completed
        if (formData.isExpired) {
          setError('Ce formulaire a expiré. Veuillez contacter le service RH pour obtenir un nouveau lien.');
        } else if (formData.isCompleted) {
          setError('Ce formulaire a déjà été soumis. Merci pour votre participation.');
        }
      } catch (err: any) {
        if (isCancelled) return;
        
        setError(
          err.response?.status === 404 
            ? 'Formulaire introuvable. Veuillez vérifier le lien ou contacter le service RH.'
            : 'Erreur lors du chargement du formulaire. Veuillez réessayer.'
        );
      } finally {
        if (!isCancelled) {
          setLoading(false);
        }
      }
    };

    // Small delay to prevent rapid re-renders
    const timeoutId = setTimeout(loadForm, 100);
    
    return () => {
      isCancelled = true;
      clearTimeout(timeoutId);
      abortController.abort();
    };
  }, [token, mounted]);

  // Redirect to external URL if provided (must be outside of render condition)
  useEffect(() => {
    if (externalUrl) {
      const url = (() => {
        try {
          const u = new URL(externalUrl);
          if (!u.searchParams.has('token') && token) {
            u.searchParams.set('token', token);
          }
          return u.toString();
        } catch {
          const sep = externalUrl.includes('?') ? '&' : '?';
          return token ? `${externalUrl}${sep}token=${encodeURIComponent(token)}` : externalUrl;
        }
      })();
      try {
        window.location.replace(url);
      } catch {}
    }
  }, [externalUrl]);

  // Handle field value change
  const handleFieldChange = (fieldName: string, value: any) => {
    setResponses(prev => ({
      ...prev,
      [fieldName]: value
    }));
    
    // Clear error for this field
    if (errors[fieldName]) {
      setErrors(prev => ({
        ...prev,
        [fieldName]: ''
      }));
    }
  };

  // Handle file upload
  const handleFileUpload = async (fieldName: string, file: File): Promise<string> => {
    try {
      const result = await candidateFormApi.uploadFormFile(token, fieldName, file);
      return result.fileUrl;
    } catch (error) {
      console.error('File upload failed:', error);
      throw new Error('Échec du téléchargement du fichier');
    }
  };

  // Validate form
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!form || !form.fields || !Array.isArray(form.fields)) return false;

    form.fields.forEach((field: FormField) => {
      const value = responses[field.name];
      
      // Required field validation
      if (field.isRequired && (!value || (Array.isArray(value) && value.length === 0))) {
        newErrors[field.name] = 'Ce champ est obligatoire';
        return;
      }

      // Skip validation if field is empty and not required
      if (!value) return;

      // Validation de base selon le type de champ
      // Remarque: Votre backend n'a pas de validation field, donc on fait de la validation basique

      // Email validation
      if (field.type === 'email' && value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
          newErrors[field.name] = 'Adresse email invalide';
        }
      }

      // Phone validation
      if (field.type === 'tel' && value) {
        const phoneRegex = /^[\d\s\-\+\(\)\.]{8,}$/;
        if (!phoneRegex.test(value)) {
          newErrors[field.name] = 'Numéro de téléphone invalide';
        }
      }
    });

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Submit form
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      enqueueSnackbar('Veuillez corriger les erreurs dans le formulaire', { variant: 'error' });
      return;
    }

    setSubmitting(true);
    
    try {
      await candidateFormApi.submitForm({
        accessToken: token,
        responses
      });
      
      setSubmitted(true);
      enqueueSnackbar('Formulaire soumis avec succès !', { variant: 'success' });
      
      // Redirect after 3 seconds
      setTimeout(() => {
        window.close(); // Try to close the tab/window
      }, 3000);
      
    } catch (err: any) {
      enqueueSnackbar(
        err.response?.data?.message || 'Erreur lors de la soumission du formulaire',
        { variant: 'error' }
      );
    } finally {
      setSubmitting(false);
    }
  };

  if (!mounted || loading) {
    return (
      <Container maxWidth="md" sx={{ py: 8 }}>
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="50vh">
          <CircularProgress />
          <Typography sx={{ ml: 2 }}>Chargement du formulaire...</Typography>
        </Box>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="md" sx={{ py: 8 }}>
        <Paper elevation={3} sx={{ p: 6, textAlign: 'center' }}>
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
          <Button 
            variant="contained" 
            onClick={() => window.close()}
            sx={{ mt: 2 }}
          >
            Fermer
          </Button>
        </Paper>
      </Container>
    );
  }

  if (externalUrl) {
    const sep = externalUrl.includes('?') ? '&' : '?';
    const urlWithToken = token ? `${externalUrl}${sep}token=${encodeURIComponent(token)}` : externalUrl;
    return (
      <Container maxWidth="sm" sx={{ py: 8 }}>
        <Paper elevation={3} sx={{ p: 4, textAlign: 'center' }}>
          <Typography variant="h6" gutterBottom>Redirection vers le formulaire externe…</Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            Si la redirection ne démarre pas automatiquement, cliquez ci-dessous.
          </Typography>
          <Button variant="contained" onClick={() => window.location.assign(urlWithToken)}>Ouvrir le formulaire</Button>
        </Paper>
      </Container>
    );
  }

  if (submitted) {
    return (
      <Container maxWidth="md" sx={{ py: 8 }}>
        <Paper elevation={3} sx={{ p: 6, textAlign: 'center' }}>
          <Alert severity="success" sx={{ mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              Formulaire soumis avec succès !
            </Typography>
            <Typography>
              Merci {form?.candidate.firstName} pour avoir complété ce formulaire. 
              Nos équipes reviendront vers vous prochainement.
            </Typography>
          </Alert>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
            Cette fenêtre va se fermer automatiquement dans quelques secondes...
          </Typography>
        </Paper>
      </Container>
    );
  }

  if (!form) {
    return (
      <Container maxWidth="md" sx={{ py: 8 }}>
        <Alert severity="error">
          Formulaire introuvable
        </Alert>
      </Container>
    );
  }

  // Debug: désactiver temporairement le rendu du formulaire interne
  console.debug('[CandidateForm] externalUrl is null. Form data received:', form);
  return (
    <Container maxWidth="md" sx={{ py: 8 }}>
      <Paper elevation={3} sx={{ p: 4 }}>
        <Typography variant="h6" gutterBottom>Mode &laquo; formulaire interne &raquo; désactivé temporairement</Typography>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          L’API n’a pas retourné d’URL externe. Nous affichons ce panneau pour debug afin de vérifier pourquoi l’URL n’est pas fournie.
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, flexDirection: 'column' }}>
          <Typography variant="body2">Titre: {form.title}</Typography>
          <Typography variant="body2">Description: {form.description || '—'}</Typography>
          <Typography variant="body2">Champs (count): {Array.isArray(form.fields) ? form.fields.length : 0}</Typography>
          <Alert severity="info">
            Assurez-vous que le backend renvoie <code>externalFormUrl</code> dans{' '}
            <code>{'GET /api/hr/public/candidate-form/{token}'}</code>.
          </Alert>
        </Box>
      </Paper>
    </Container>
  );
}
