import { useState } from 'react';
import { downloadTrack, TrackDownloadError } from '../services/trackDownloadService';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useToast } from '@/hooks/useToast';
import { Download, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * TrackDownloadButton Component
 * T0315: Composant pour télécharger un track avec indicateur de progression et gestion d'erreurs
 */

interface TrackDownloadButtonProps {
  trackId: number;
  shareToken?: string;
  filename?: string;
  variant?: 'default' | 'outline' | 'ghost' | 'secondary' | 'destructive' | 'link';
  size?: 'default' | 'sm' | 'lg' | 'icon';
  className?: string;
  showProgress?: boolean;
  onDownloadStart?: () => void;
  onDownloadComplete?: () => void;
  onDownloadError?: (error: string) => void;
}

export function TrackDownloadButton({
  trackId,
  shareToken,
  filename,
  variant = 'default',
  size = 'default',
  className,
  showProgress = false,
  onDownloadStart,
  onDownloadComplete,
  onDownloadError,
}: TrackDownloadButtonProps) {
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  const handleDownload = async () => {
    setLoading(true);
    setError(null);
    setProgress(0);

    if (onDownloadStart) {
      onDownloadStart();
    }

    try {
      await downloadTrack(trackId, {
        shareToken,
        filename,
        onProgress: showProgress
          ? (progressValue) => {
              setProgress(progressValue);
            }
          : undefined,
      });

      toast.success('Téléchargement terminé');
      if (onDownloadComplete) {
        onDownloadComplete();
      }
    } catch (err) {
      let errorMessage = 'Échec du téléchargement';
      if (err instanceof TrackDownloadError) {
        errorMessage = err.message;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }

      setError(errorMessage);
      toast.error(errorMessage);

      if (onDownloadError) {
        onDownloadError(errorMessage);
      }
    } finally {
      setLoading(false);
      setProgress(0);
    }
  };

  return (
    <div className={cn('space-y-2', className)}>
      <Button
        onClick={handleDownload}
        disabled={loading}
        variant={variant}
        size={size}
        className={cn('relative', className)}
      >
        {loading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            {showProgress && progress > 0 ? (
              <span>Téléchargement... {progress}%</span>
            ) : (
              <span>Téléchargement...</span>
            )}
          </>
        ) : (
          <>
            <Download className="mr-2 h-4 w-4" />
            <span>Télécharger</span>
          </>
        )}
      </Button>

      {/* Barre de progression */}
      {showProgress && loading && progress > 0 && (
        <div className="w-full bg-muted rounded-full h-2">
          <div
            className="bg-primary h-2 rounded-full transition-all duration-300"
            style={{ width: `${progress}%` }}
            role="progressbar"
            aria-valuenow={progress}
            aria-valuemin={0}
            aria-valuemax={100}
          />
        </div>
      )}

      {/* Affichage d'erreur */}
      {error && (
        <Alert variant="destructive" className="mt-2">
          <AlertDescription className="text-sm">{error}</AlertDescription>
        </Alert>
      )}
    </div>
  );
}

