import React, { useMemo } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { TrackCard } from '@/components/music/TrackCard';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { 
  Play, 
  Pause, 
  Trash2, 
  MoreVertical,
  Clock,
  FileAudio,
  Volume2,
  Download,
  Edit
} from 'lucide-react';
import { type Track } from '@/services/api';

interface VirtualLibraryGridProps {
  tracks: Track[];
  viewMode: 'grid' | 'list';
  onTrackSelect?: (track: Track) => void;
  onTrackDelete?: (trackId: string) => void;
  onTrackEdit?: (track: Track) => void;
  isPlaying?: (trackId: string) => boolean;
  parentRef: React.RefObject<HTMLDivElement>;
}

export function VirtualLibraryGrid({
  tracks,
  viewMode,
  onTrackSelect,
  onTrackDelete,
  onTrackEdit,
  isPlaying,
  parentRef
}: VirtualLibraryGridProps) {
  const virtualizer = useVirtualizer({
    count: tracks.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => viewMode === 'grid' ? 280 : 80,
    overscan: 5,
  });

  const items = virtualizer.getVirtualItems();

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatFileSize = (bytes: number) => {
    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 parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (viewMode === 'grid') {
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {items.map((virtualItem) => {
          const track = tracks[virtualItem.index];
          return (
            <div
              key={track.id}
              style={{
                height: `${virtualItem.size}px`,
                transform: `translateY(${virtualItem.start}px)`,
              }}
            >
              <TrackCard
                track={track}
                size="large"
                onPlay={() => onTrackSelect?.(track)}
                onEdit={() => onTrackEdit?.(track)}
                onDelete={() => onTrackDelete?.(track.id)}
                isPlaying={isPlaying?.(track.id) || false}
                className="h-full"
              />
            </div>
          );
        })}
      </div>
    );
  }

  // List view
  return (
    <div className="space-y-2">
      {items.map((virtualItem) => {
        const track = tracks[virtualItem.index];
        const playing = isPlaying?.(track.id) || false;
        
        return (
          <div
            key={track.id}
            style={{
              height: `${virtualItem.size}px`,
              transform: `translateY(${virtualItem.start}px)`,
            }}
          >
            <Card className="group hover:shadow-lg transition-all duration-200 cursor-pointer">
              <CardContent className="p-4">
                <div className="flex items-center space-x-4">
                  {/* Cover */}
                  <div className="relative w-12 h-12 rounded-lg overflow-hidden bg-gradient-to-br from-purple-500 to-pink-500 flex-shrink-0">
                    {track.coverUrl ? (
                      <img
                        src={track.coverUrl}
                        alt={track.title}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-white font-bold text-lg">
                        {track.title.charAt(0).toUpperCase()}
                      </div>
                    )}
                    <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 flex items-center justify-center">
                      <Button
                        size="sm"
                        variant="ghost"
                        className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-white hover:text-white hover:bg-white/20"
                        onClick={() => onTrackSelect?.(track)}
                      >
                        {playing ? (
                          <Pause className="h-4 w-4" />
                        ) : (
                          <Play className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  </div>

                  {/* Track Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-2">
                      <h3 className="font-semibold text-sm truncate">{track.title}</h3>
                      {playing && (
                        <Badge variant="secondary" className="text-xs">
                          <Activity className="h-3 w-3 mr-1" />
                          En cours
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground truncate">{track.artist}</p>
                    <div className="flex items-center space-x-4 mt-1">
                      <span className="text-xs text-muted-foreground flex items-center">
                        <Clock className="h-3 w-3 mr-1" />
                        {formatDuration(track.duration)}
                      </span>
                      <span className="text-xs text-muted-foreground flex items-center">
                        <FileAudio className="h-3 w-3 mr-1" />
                        {track.format}
                      </span>
                      <span className="text-xs text-muted-foreground flex items-center">
                        <Volume2 className="h-3 w-3 mr-1" />
                        {track.bitrate}k
                      </span>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center space-x-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => onTrackEdit?.(track)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => onTrackDelete?.(track.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                    >
                      <MoreVertical className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        );
      })}
    </div>
  );
}
