import { useEffect, useState } from 'react';
import { getTrackStats, TrackStats } from '../services/analyticsService';
import { TrackServiceError as TrackStatsError } from '../errors/trackErrors';
import { Eye, Heart, MessageCircle, Download, Clock, Loader2 } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { cn } from '@/lib/utils';

interface TrackStatsDisplayProps {
  trackId: number;
  className?: string;
  variant?: 'horizontal' | 'vertical' | 'grid';
  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) {
        setError(err instanceof TrackStatsError ? err.message : 'Telemetry interrupted');
      } 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="flex h-10 items-center gap-2 text-xs font-mono text-primary animate-pulse"><Loader2 className="w-3 h-3 animate-spin" /> SCANNING...</div>;
  if (error || !stats) return null;

  const statsItems = [
    { icon: Eye, value: formatNumber(stats.views), label: 'Views', color: 'text-cyan-500', bg: 'bg-cyan-500/10' },
    { icon: Heart, value: formatNumber(stats.likes), label: 'Likes', color: 'text-magenta-500', bg: 'bg-magenta-500/10' },
    { icon: MessageCircle, value: formatNumber(stats.comments), label: 'Comms', color: 'text-lime-500', bg: 'bg-lime-500/10' },
    { icon: Download, value: formatNumber(stats.downloads), label: 'Data', color: 'text-gold-500', bg: 'bg-gold-500/10' },
    { icon: Clock, value: formatDuration(stats.total_play_time), label: 'Pulse', color: 'text-primary', bg: 'bg-primary/10' },
  ];

  if (variant === 'grid') {
    return (
      <div className={cn("grid grid-cols-2 md:grid-cols-5 gap-3", className)}>
        {statsItems.map((item, i) => {
          const Icon = item.icon;
          return (
            <Card key={i} variant="glass" className="p-3 bg-black/40 border-white/5 flex flex-col items-center gap-1 group hover:border-white/20 transition-all">
              <div className={cn("p-2 rounded-lg mb-1 group-hover:scale-110 transition-transform", item.bg, item.color)}><Icon className="w-4 h-4" /></div>
              <div className="text-lg font-display font-bold text-white">{item.value}</div>
              <div className="text-[8px] font-mono text-muted-foreground uppercase tracking-widest">{item.label}</div>
            </Card>
          );
        })}
      </div>
    );
  }

  return (
    <div className={cn("flex flex-wrap items-center gap-6", className)}>
      {statsItems.map((item, i) => {
        const Icon = item.icon;
        return (
          <div key={i} className="flex items-center gap-2 group cursor-default">
            <div className={cn("p-1.5 rounded bg-white/5 opacity-60 group-hover:opacity-100 transition-all", item.color)}><Icon className="w-3.5 h-3.5" /></div>
            <div className="flex flex-col">
              <span className="text-sm font-bold text-white group-hover:text-primary transition-colors">{item.value}</span>
              {showLabels && <span className="text-[8px] font-mono text-muted-foreground uppercase tracking-wider">{item.label}</span>}
            </div>
          </div>
        );
      })}
    </div>
  );
}
