import { useState, useRef, useCallback, useEffect } from 'react';
import { uploadTrack, getUploadProgress, resumeUpload, TrackUploadError, UploadResumeState } from '../services/trackService';
import { ChunkedUploadManager, calculateTotalChunks, CHUNK_SIZE } from '../services/chunkedUploadService';
import { Track, UploadProgress, TrackStatus } from '../types/track';
import { UploadQuota } from './UploadQuota';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/feedback/Progress';
import { Card, CardContent } from '@/components/ui/card';
import { useToast } from '@/hooks/useToast';
import { useAuthStore } from '@/stores/auth';
import { Upload, Music, X, CheckCircle, AlertCircle, Loader2, Pause, Play, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * TrackUpload Component
 * T0261: Composant pour uploader des tracks avec drag & drop, preview, et progress tracking
 */

interface TrackUploadProps {
  onUploadComplete?: (track: Track) => void;
  className?: string;
}

const ALLOWED_AUDIO_TYPES = ['audio/mpeg', 'audio/flac', 'audio/wav', 'audio/ogg', 'audio/m4a', 'audio/aac'];
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
const CHUNKED_UPLOAD_THRESHOLD = 20 * 1024 * 1024; // Utiliser upload par chunks pour fichiers > 20MB
const UPLOAD_STATE_KEY = 'veza_upload_state'; // Clé pour localStorage

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${Math.round((bytes / Math.pow(k, i)) * 100) / 100  } ${  sizes[i]}`;
};

const getFileFormat = (file: File): string => {
  const ext = file.name.split('.').pop()?.toUpperCase();
  return ext || 'UNKNOWN';
};

const formatTimeRemaining = (seconds: number): string => {
  if (seconds < 60) {
    return `${Math.ceil(seconds)}s`;
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.ceil(seconds % 60);
    return `${minutes}m ${secs}s`;
  } else {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}h ${minutes}m`;
  }
};

export function TrackUpload({ onUploadComplete, className }: TrackUploadProps) {
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [trackId, setTrackId] = useState<number | null>(null);
  const [trackStatus, setTrackStatus] = useState<TrackStatus | null>(null);
  const [statusMessage, setStatusMessage] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const chunkedUploadManagerRef = useRef<ChunkedUploadManager | null>(null);
  const [isPaused, setIsPaused] = useState(false);
  const [useChunkedUpload, setUseChunkedUpload] = useState(false);
  const [uploadSpeed, setUploadSpeed] = useState(0); // MB/s
  const [timeRemaining, setTimeRemaining] = useState<number | null>(null); // seconds
  const [currentStep, setCurrentStep] = useState<'uploading' | 'processing'>('uploading');
  const uploadStartTimeRef = useRef<number | null>(null);
  const lastProgressRef = useRef<{ progress: number; time: number } | null>(null);
  const retryCountRef = useRef<number>(0);
  const maxRetries = 3;
  const retryDelay = 2000; // 2 secondes
  const { toast } = useToast();
  const { user } = useAuthStore();
  const [quotaKey, setQuotaKey] = useState(0); // Force re-render du quota après upload
  const [uploadId, setUploadId] = useState<string | null>(null); // ID de l'upload en cours

  // Interface pour l'état sauvegardé dans localStorage
  interface SavedUploadState {
    uploadId: string;
    fileName: string;
    fileSize: number;
    timestamp: number;
  }

  // Sauvegarder l'état de l'upload dans localStorage
  const saveUploadState = useCallback((id: string, selectedFile: File) => {
    const state: SavedUploadState = {
      uploadId: id,
      fileName: selectedFile.name,
      fileSize: selectedFile.size,
      timestamp: Date.now(),
    };
    localStorage.setItem(UPLOAD_STATE_KEY, JSON.stringify(state));
    setUploadId(id);
  }, []);

  // Charger l'état de l'upload depuis localStorage
  const loadUploadState = useCallback((): SavedUploadState | null => {
    try {
      const saved = localStorage.getItem(UPLOAD_STATE_KEY);
      if (!saved) return null;
      
      const state: SavedUploadState = JSON.parse(saved);
      // Vérifier que l'état n'est pas trop ancien (24 heures)
      const maxAge = 24 * 60 * 60 * 1000; // 24 heures
      if (Date.now() - state.timestamp > maxAge) {
        localStorage.removeItem(UPLOAD_STATE_KEY);
        return null;
      }
      return state;
    } catch (error) {
      console.error('Error loading upload state:', error);
      localStorage.removeItem(UPLOAD_STATE_KEY);
      return null;
    }
  }, []);

  // Effacer l'état sauvegardé
  const clearUploadState = useCallback(() => {
    localStorage.removeItem(UPLOAD_STATE_KEY);
    setUploadId(null);
  }, []);

  // Détecter les uploads en cours au chargement
  useEffect(() => {
    const savedState = loadUploadState();
    if (savedState && user) {
      // Vérifier si l'upload existe toujours côté serveur
      resumeUpload(savedState.uploadId)
        .then((resumeState) => {
          // L'upload existe toujours, proposer de le reprendre
          if (resumeState.progress < 100) {
            toast({
              title: 'Upload en pause détecté',
              description: `Voulez-vous reprendre l'upload de "${resumeState.filename}" ?`,
              duration: 10000,
            });
          } else {
            // L'upload est terminé, nettoyer
            clearUploadState();
          }
        })
        .catch((error) => {
          // L'upload n'existe plus ou a expiré, nettoyer
          console.error('Upload state not found:', error);
          clearUploadState();
        });
    }
  }, [user, loadUploadState, clearUploadState, toast]);

  // Cleanup polling on unmount
  useEffect(() => {
    return () => {
      if (pollingIntervalRef.current) {
        clearInterval(pollingIntervalRef.current);
      }
    };
  }, []);

  const validateFile = (selectedFile: File): string | null => {
    // Validation du format
    if (!ALLOWED_AUDIO_TYPES.includes(selectedFile.type)) {
      // Vérifier aussi par extension au cas où le type MIME n'est pas défini
      const ext = selectedFile.name.split('.').pop()?.toLowerCase();
      const allowedExtensions = ['mp3', 'flac', 'wav', 'ogg', 'm4a', 'aac'];
      if (!ext || !allowedExtensions.includes(ext)) {
        return 'Format non supporté. Formats acceptés: MP3, FLAC, WAV, OGG, M4A, AAC';
      }
    }

    // Validation de la taille
    if (selectedFile.size > MAX_FILE_SIZE) {
      return `Fichier trop volumineux. Taille maximale: ${formatFileSize(MAX_FILE_SIZE)}`;
    }

    if (selectedFile.size === 0) {
      return 'Le fichier est vide';
    }

    return null;
  };

  const handleFileSelect = useCallback(async (selectedFile: File) => {
    // Reset error
    setError(null);

    // Validation
    const validationError = validateFile(selectedFile);
    if (validationError) {
      setError(validationError);
      toast.error(validationError);
      return;
    }

    setFile(selectedFile);
    setUploadProgress(0);
    setTrackStatus(null);
    setStatusMessage(null);
    setIsPaused(false);
    setUploadSpeed(0);
    setTimeRemaining(null);
    setCurrentStep('uploading');
    uploadStartTimeRef.current = Date.now();
    lastProgressRef.current = null;

    // Décider si on utilise l'upload par chunks
    const shouldUseChunkedUpload = selectedFile.size > CHUNKED_UPLOAD_THRESHOLD;
    setUseChunkedUpload(shouldUseChunkedUpload);

    // Upload avec retry automatique
    await handleUploadWithRetry(selectedFile, shouldUseChunkedUpload);
  }, [toast]);

  const handleUploadWithRetry = useCallback(async (
    selectedFile: File,
    useChunked: boolean,
    attempt: number = 1
  ): Promise<void> => {
    try {
      setUploading(true);
      setTrackStatus('uploading');
      setCurrentStep('uploading');
      setError(null);

      if (useChunked) {
        // Upload par chunks
        await handleChunkedUpload(selectedFile);
      } else {
        // Upload normal
        setStatusMessage('Upload en cours...');

        const track = await uploadTrack(selectedFile, (progress) => {
          setUploadProgress(progress);
          
          // Calculer vitesse upload et temps restant
          const now = Date.now();
          const startTime = uploadStartTimeRef.current || now;
          const elapsed = (now - startTime) / 1000; // seconds
          
          if (elapsed > 0 && progress > 0) {
            const uploaded = (selectedFile.size * progress) / 100;
            const speed = uploaded / elapsed / 1024 / 1024; // MB/s
            setUploadSpeed(speed);
            
            // Utiliser la vitesse moyenne pour calculer le temps restant
            if (progress < 100 && speed > 0) {
              const remaining = selectedFile.size - uploaded;
              const remainingTime = remaining / (speed * 1024 * 1024); // seconds
              setTimeRemaining(remainingTime);
            } else {
              setTimeRemaining(null);
            }
          }
          
          lastProgressRef.current = { progress, time: now };
        });

        setTrackId(track.id);
        setUploadProgress(100);
        setCurrentStep('processing');
        setTimeRemaining(null);
        retryCountRef.current = 0; // Reset retry count on success

        // Démarrer le polling pour suivre le statut
        startPolling(track.id);
      }
    } catch (err) {
      // Gérer les erreurs avec retry automatique
      if (err instanceof TrackUploadError) {
        const errorMessage = getErrorMessage(err);
        setError(errorMessage);
        setUploadSpeed(0);
        setTimeRemaining(null);
        
        // Retry automatique pour les erreurs réseau/serveur retryable
        if (err.retryable && attempt < maxRetries) {
          retryCountRef.current = attempt;
          setStatusMessage(`Tentative ${attempt + 1}/${maxRetries}...`);
          toast.warning(`${errorMessage} Nouvelle tentative dans ${retryDelay / 1000}s...`);
          
          // Attendre avant de retry
          await new Promise(resolve => setTimeout(resolve, retryDelay));
          
          // Retry
          await handleUploadWithRetry(selectedFile, useChunked, attempt + 1);
          return;
        }
        
        // Si pas de retry ou max retries atteint
        setUploading(false);
        setTrackStatus('failed');
        setStatusMessage(errorMessage);
        toast.error(errorMessage);
      } else {
        // Erreur inconnue
        const errorMessage = err instanceof Error ? err.message : 'Erreur lors de l\'upload';
        setError(errorMessage);
        setUploading(false);
        setTrackStatus('failed');
        setStatusMessage(errorMessage);
        setUploadSpeed(0);
        setTimeRemaining(null);
        toast.error(errorMessage);
      }
    }
  }, [toast]);

  const getErrorMessage = useCallback((error: TrackUploadError): string => {
    switch (error.code) {
      case 'VALIDATION':
        return error.message || 'Erreur de validation: Format ou taille de fichier invalide';
      case 'QUOTA':
        return error.message || 'Quota upload atteint. Vous avez atteint votre limite d\'upload.';
      case 'NETWORK':
        return error.message || 'Erreur réseau: Impossible de se connecter au serveur. Vérifiez votre connexion.';
      case 'SERVER':
        return error.message || 'Erreur serveur: Le serveur rencontre un problème. Veuillez réessayer plus tard.';
      default:
        return error.message || 'Erreur inconnue lors de l\'upload';
    }
  }, []);

  const handleChunkedUpload = useCallback(async (selectedFile: File, resumeState?: UploadResumeState) => {
    const totalChunks = calculateTotalChunks(selectedFile.size);
    setStatusMessage(`Upload par chunks (${totalChunks} chunks)...`);

    const manager = new ChunkedUploadManager(selectedFile, (progress) => {
      setUploadProgress(progress.progress);
      
      // Calculer vitesse upload et temps restant pour chunked upload
      const now = Date.now();
      const startTime = uploadStartTimeRef.current || now;
      const elapsed = (now - startTime) / 1000; // seconds
      
      if (elapsed > 0 && progress.progress > 0) {
        const uploaded = (selectedFile.size * progress.progress) / 100;
        const speed = uploaded / elapsed / 1024 / 1024; // MB/s
        setUploadSpeed(speed);
        
        if (progress.progress < 100 && speed > 0) {
          const remaining = selectedFile.size - uploaded;
          const remainingTime = remaining / (speed * 1024 * 1024); // seconds
          setTimeRemaining(remainingTime);
        } else {
          setTimeRemaining(null);
        }
      }
      
      setStatusMessage(
        `Upload en cours: ${progress.uploadedChunks}/${progress.totalChunks} chunks ${ 
        progress.failedChunks > 0 ? `(${progress.failedChunks} échoués)` : ''}`
      );
    });

    chunkedUploadManagerRef.current = manager;

    // Si on reprend un upload, restaurer l'état
    if (resumeState) {
      // Définir l'uploadId
      manager.setUploadId(resumeState.upload_id);
      setUploadId(resumeState.upload_id);
      
      // Marquer les chunks déjà reçus comme uploadés
      manager.setUploadedChunks(resumeState.chunks_received);
      
      saveUploadState(resumeState.upload_id, selectedFile);
    }

    try {
      await manager.start();
      
      // Sauvegarder l'uploadId après l'initiation si ce n'est pas une reprise
      if (!resumeState && manager.getState().uploadId) {
        saveUploadState(manager.getState().uploadId, selectedFile);
      }

      const state = manager.getState();
      if (state.isComplete) {
        setUploadProgress(100);
        setTrackStatus('completed');
        setStatusMessage('Upload terminé avec succès');
        setCurrentStep('processing');
        setUploadSpeed(0);
        setTimeRemaining(null);
        setUploading(false);
        toast.success('Upload terminé avec succès');

        // Appeler le callback si fourni
        if (onUploadComplete) {
          const track: Track = {
            id: 0, // Sera récupéré depuis l'API si nécessaire
            user_id: 0,
            title: selectedFile.name.replace(/\.[^/.]+$/, ''),
            artist: '',
            duration: 0,
            file_path: '',
            file_size: selectedFile.size,
            format: getFileFormat(selectedFile),
            is_public: true,
            play_count: 0,
            like_count: 0,
            status: 'completed',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          };
          onUploadComplete(track);
          // Recharger le quota après upload réussi
          setQuotaKey(prev => prev + 1);
        }
      } else if (state.error) {
        throw new TrackUploadError(state.error, 'UNKNOWN', false);
      }
    } catch (err) {
      setUploadSpeed(0);
      setTimeRemaining(null);
      
      // Si c'est déjà une TrackUploadError, la relancer
      if (err instanceof TrackUploadError) {
        throw err;
      }
      
      // Sinon, créer une nouvelle TrackUploadError
      const errorMessage = err instanceof Error ? err.message : 'Erreur lors de l\'upload par chunks';
      throw new TrackUploadError(errorMessage, 'UNKNOWN', false, err);
    } finally {
      // Nettoyer l'état sauvegardé si l'upload est terminé ou échoué
      const finalState = manager.getState();
      if (finalState.isComplete || finalState.error) {
        clearUploadState();
      }
    }
  }, [toast, onUploadComplete, file, saveUploadState, clearUploadState]);

  const handlePauseResume = useCallback(async () => {
    if (!chunkedUploadManagerRef.current || !file) return;

    if (isPaused) {
      // Reprendre l'upload
      setIsPaused(false);
      
      // Si on a un uploadId, essayer de reprendre depuis le serveur
      if (uploadId) {
        try {
          const resumeState = await resumeUpload(uploadId);
          // Reprendre avec l'état du serveur
          await handleChunkedUpload(file, resumeState);
        } catch (error) {
          // Si l'upload n'existe plus, reprendre normalement
          console.error('Error resuming upload:', error);
          await chunkedUploadManagerRef.current.resume();
        }
      } else {
        await chunkedUploadManagerRef.current.resume();
      }
    } else {
      // Mettre en pause
      setIsPaused(true);
      chunkedUploadManagerRef.current.pause();
      
      // Sauvegarder l'état si on a un uploadId
      if (uploadId && file) {
        saveUploadState(uploadId, file);
      }
    }
  }, [isPaused, file, uploadId, handleChunkedUpload, saveUploadState]);

  const startPolling = useCallback((id: number) => {
    // Nettoyer l'intervalle précédent s'il existe
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
    }

    pollingIntervalRef.current = setInterval(async () => {
      try {
        const progress = await getUploadProgress(id);
        setTrackStatus(progress.status);
        setStatusMessage(progress.message || null);
        setUploadProgress(progress.progress);

        if (progress.status === 'completed') {
          if (pollingIntervalRef.current) {
            clearInterval(pollingIntervalRef.current);
            pollingIntervalRef.current = null;
          }
          setUploading(false);
          toast.success('Upload terminé avec succès');
          
          // Appeler le callback si fourni
          if (onUploadComplete && file) {
            // Récupérer les infos complètes du track depuis l'API si nécessaire
            // Pour l'instant, on utilise juste l'ID
            const track: Track = {
              id: progress.track_id,
              user_id: 0, // Sera mis à jour par l'API
              title: file.name.replace(/\.[^/.]+$/, ''),
              artist: '',
              duration: 0,
              file_path: '',
              file_size: file.size,
              format: getFileFormat(file),
              is_public: true,
              play_count: 0,
              like_count: 0,
              status: 'completed',
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
            };
            onUploadComplete(track);
            // Recharger le quota après upload réussi
            setQuotaKey(prev => prev + 1);
          }
        } else if (progress.status === 'failed') {
          if (pollingIntervalRef.current) {
            clearInterval(pollingIntervalRef.current);
            pollingIntervalRef.current = null;
          }
          setUploading(false);
          const errorMsg = progress.message || 'Upload échoué';
          setError(errorMsg);
          toast.error(errorMsg);
        }
      } catch (err) {
        console.error('Error polling upload status:', err);
        // Continuer le polling même en cas d'erreur temporaire
      }
    }, 2000); // Poll toutes les 2 secondes
  }, [file, onUploadComplete, toast]);

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (uploading) return;

    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      const droppedFile = e.dataTransfer.files[0];
      handleFileSelect(droppedFile);
    }
  }, [uploading, handleFileSelect]);

  const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFileSelect(e.target.files[0]);
      // Réinitialiser l'input pour permettre la sélection du même fichier
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  }, [handleFileSelect]);

  const handleReset = useCallback(() => {
    setFile(null);
    setUploading(false);
    setUploadProgress(0);
    setTrackId(null);
    setTrackStatus(null);
    setStatusMessage(null);
    setError(null);
    setIsPaused(false);
    setUseChunkedUpload(false);
    setUploadSpeed(0);
    setTimeRemaining(null);
    setCurrentStep('uploading');
    setError(null);
    uploadStartTimeRef.current = null;
    lastProgressRef.current = null;
    retryCountRef.current = 0;
    clearUploadState(); // Nettoyer l'état sauvegardé
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
    if (chunkedUploadManagerRef.current) {
      chunkedUploadManagerRef.current.cancel();
      chunkedUploadManagerRef.current = null;
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }, [clearUploadState]);

  const handleClick = () => {
    if (!uploading && fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  // Recharger le quota après un upload réussi
  const handleQuotaUpdated = useCallback(() => {
    setQuotaKey(prev => prev + 1);
  }, []);

  return (
    <div className={cn('w-full space-y-4', className)}>
      {/* Affichage du quota */}
      {user && (
        <UploadQuota
          key={quotaKey}
          userId={user.id}
          onQuotaUpdated={handleQuotaUpdated}
        />
      )}

      {/* Zone de drag & drop */}
      <Card
        className={cn(
          'border-2 border-dashed transition-colors cursor-pointer',
          dragActive && 'border-primary bg-primary/5',
          uploading && 'opacity-50 cursor-not-allowed',
          !uploading && 'hover:border-primary/50'
        )}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
        onClick={handleClick}
      >
        <CardContent className="flex flex-col items-center justify-center p-8 text-center">
          <Upload className={cn('h-12 w-12 mb-4 text-muted-foreground', dragActive && 'text-primary')} />
          <p className="text-lg font-medium mb-2">
            Glissez-déposez un fichier audio ici, ou cliquez pour sélectionner
          </p>
          <p className="text-sm text-muted-foreground mb-4">
            Formats acceptés: MP3, FLAC, WAV, OGG, M4A, AAC • Taille maximale: {formatFileSize(MAX_FILE_SIZE)}
          </p>
          <Button type="button" variant="outline" disabled={uploading}>
            {uploading ? 'Upload en cours...' : 'Sélectionner un fichier'}
          </Button>
        </CardContent>
      </Card>

      {/* Input file caché */}
      <input
        ref={fileInputRef}
        type="file"
        accept="audio/*,.mp3,.flac,.wav,.ogg,.m4a,.aac"
        onChange={handleFileInput}
        disabled={uploading}
        className="hidden"
      />

      {/* Message d'erreur */}
      {error && (
        <Card className="border-destructive bg-destructive/10">
          <CardContent className="flex flex-col gap-2 p-4">
            <div className="flex items-center gap-2 text-sm text-destructive">
              <AlertCircle className="h-4 w-4 shrink-0" />
              <span className="flex-1">{error}</span>
            </div>
            {!uploading && file && (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  if (file) {
                    handleFileSelect(file);
                  }
                }}
                className="self-start"
              >
                <RefreshCw className="h-3 w-3 mr-1" />
                Réessayer
              </Button>
            )}
          </CardContent>
        </Card>
      )}

      {/* Preview du fichier sélectionné */}
      {file && (
        <Card>
          <CardContent className="p-4">
            <div className="flex items-start gap-4">
              {/* Icône */}
              <div className="shrink-0">
                <div className="w-16 h-16 flex items-center justify-center bg-muted rounded-md">
                  <Music className="h-8 w-8 text-muted-foreground" />
                </div>
              </div>

              {/* Info fichier */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between mb-1">
                  <p className="text-sm font-medium truncate">{file.name}</p>
                  {!uploading && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6 shrink-0"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleReset();
                      }}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                </div>
                <p className="text-xs text-muted-foreground mb-2">
                  {formatFileSize(file.size)} • {getFileFormat(file)}
                </p>

                {/* Progress bar */}
                {(uploading || trackStatus) && (
                  <div className="space-y-2">
                    <Progress value={uploadProgress} showLabel />
                    {statusMessage && (
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        {trackStatus === 'uploading' && <Loader2 className="h-3 w-3 animate-spin" />}
                        {trackStatus === 'processing' && <Loader2 className="h-3 w-3 animate-spin" />}
                        {trackStatus === 'completed' && <CheckCircle className="h-3 w-3 text-green-600" />}
                        {trackStatus === 'failed' && <AlertCircle className="h-3 w-3 text-destructive" />}
                        <span>{statusMessage}</span>
                      </p>
                    )}
                    
                    {/* Informations de progression avancées */}
                    {(uploading || trackStatus === 'uploading') && currentStep === 'uploading' && (
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        {uploadSpeed > 0 && (
                          <span>
                            Vitesse: {uploadSpeed.toFixed(2)} MB/s
                          </span>
                        )}
                        {timeRemaining !== null && timeRemaining > 0 && (
                          <span>
                            Temps restant: {formatTimeRemaining(timeRemaining)}
                          </span>
                        )}
                        <span className="capitalize">
                          Étape: {currentStep === 'uploading' ? 'Upload' : 'Traitement'}
                        </span>
                      </div>
                    )}
                    
                    {currentStep === 'processing' && (
                      <div className="text-xs text-muted-foreground">
                        Étape: Traitement en cours...
                      </div>
                    )}
                    
                    {/* Bouton pause/resume pour upload par chunks */}
                    {useChunkedUpload && uploading && !trackStatus && (
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={handlePauseResume}
                        className="mt-2"
                      >
                        {isPaused ? (
                          <>
                            <Play className="h-3 w-3 mr-1" />
                            Reprendre
                          </>
                        ) : (
                          <>
                            <Pause className="h-3 w-3 mr-1" />
                            Pause
                          </>
                        )}
                      </Button>
                    )}
                  </div>
                )}

                {/* Status badge */}
                {trackStatus === 'completed' && (
                  <div className="flex items-center gap-1 text-xs text-green-600 mt-2">
                    <CheckCircle className="h-3 w-3" />
                    <span>Upload terminé avec succès</span>
                  </div>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

