import { useEffect, useState } from 'react';
import { getTrackStats, TrackStats } from '../services/analyticsService';
import { TrackServiceError as TrackStatsError } from '../errors/trackErrors';
import { Eye, Heart, MessageCircle, Download, Clock } from 'lucide-react';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { cn } from '@/lib/utils';

/**
 * TrackStatsDisplay Component
 * T0318: Composant pour afficher les statistiques d'un track avec icônes et formatage des nombres
 */

interface TrackStatsDisplayProps {
  trackId: number;
  className?: string;
  variant?: 'horizontal' | 'vertical';
  showLabels?: boolean;
}

export function TrackStatsDisplay({
  trackId,
  className,
  variant = 'horizontal',
  showLabels = false,
}: TrackStatsDisplayProps) {
  const [stats, setStats] = useState<TrackStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadStats = async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await getTrackStats(trackId);
        setStats(data);
      } catch (err) {
        if (err instanceof TrackStatsError) {
          setError(err.message);
        } else {
          setError('Impossible de charger les statistiques');
        }
      } finally {
        setLoading(false);
      }
    };

    loadStats();
  }, [trackId]);

  const formatNumber = (n: number): string => {
    if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
    if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
    return n.toString();
  };

  const formatDuration = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    if (hours > 0) {
      return `${hours}h ${minutes}m`;
    }
    if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    }
    return `${secs}s`;
  };

  if (loading) {
    return (
      <div className={cn('flex items-center justify-center p-4', className)}>
        <LoadingSpinner size="sm" />
      </div>
    );
  }

  if (error) {
    return (
      <Alert variant="destructive" className={className}>
        <AlertDescription className="text-sm">{error}</AlertDescription>
      </Alert>
    );
  }

  if (!stats) {
    return null;
  }

  const statsItems = [
    {
      icon: Eye,
      value: formatNumber(stats.views),
      label: 'Vues',
      rawValue: stats.views,
    },
    {
      icon: Heart,
      value: formatNumber(stats.likes),
      label: 'Likes',
      rawValue: stats.likes,
    },
    {
      icon: MessageCircle,
      value: formatNumber(stats.comments),
      label: 'Commentaires',
      rawValue: stats.comments,
    },
    {
      icon: Download,
      value: formatNumber(stats.downloads),
      label: 'Téléchargements',
      rawValue: stats.downloads,
    },
    {
      icon: Clock,
      value: formatDuration(stats.total_play_time),
      label: "Temps d'écoute",
      rawValue: stats.total_play_time,
    },
  ];

  if (variant === 'vertical') {
    return (
      <div className={cn('space-y-3', className)}>
        {statsItems.map((item, index) => {
          const Icon = item.icon;
          return (
            <div key={index} className="flex items-center gap-2">
              <Icon className="h-4 w-4 text-muted-foreground" />
              <div className="flex-1">
                {showLabels && (
                  <div className="text-xs text-muted-foreground">
                    {item.label}
                  </div>
                )}
                <div className="text-sm font-medium">{item.value}</div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div className={cn('flex flex-wrap gap-4', className)}>
      {statsItems.map((item, index) => {
        const Icon = item.icon;
        return (
          <div key={index} className="flex items-center gap-1.5">
            <Icon className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">{item.value}</span>
            {showLabels && (
              <span className="text-xs text-muted-foreground ml-1">
                {item.label}
              </span>
            )}
          </div>
        );
      })}
    </div>
  );
}
