import React, { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { UploadModal } from './UploadModal';
import { TrackEditDialog } from '@/features/tracks/components/TrackEditDialog';
import { WaveformDisplay } from '@/features/tracks/components/WaveformDisplay';
import { VirtualLibraryGrid } from './VirtualLibraryGrid';
import { apiService, type Track } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import { 
  Loader2, 
  Plus, 
  Music, 
  Play, 
  Pause, 
  Trash2, 
  Upload, 
  Search,
  Filter,
  Grid,
  List,
  MoreVertical,
  Clock,
  FileAudio,
  Volume2,
  Download,
  Edit,
  Activity
} from 'lucide-react';

interface LibraryManagerProps {
  onTrackSelect?: (track: Track) => void;
}

export function LibraryManager({ onTrackSelect }: LibraryManagerProps) {
  const [tracks, setTracks] = useState<Track[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDeletingTrack, setIsDeletingTrack] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [filterType, setFilterType] = useState<string>('all');
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 20,
    total: 0,
  });
  const [selectedTrack, setSelectedTrack] = useState<Track | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [expandedWaveform, setExpandedWaveform] = useState<string | null>(null);
  const [playingTrackId, setPlayingTrackId] = useState<string | null>(null);
  const parentRef = useRef<HTMLDivElement>(null);
  const { toast } = useToast();

  const fetchTracks = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await apiService.getTracks({
        page: pagination.page,
        limit: pagination.limit,
        search: searchQuery || undefined,
        artist: filterType !== 'all' ? filterType : undefined,
      });
      setTracks(response.tracks);
      setPagination(prev => ({
        ...prev,
        total: response.total,
      }));
    } catch (err: any) {
      setError(err.response?.data?.error || err.message || 'Failed to fetch tracks');
      console.error('Error fetching tracks:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchTracks();
  }, [pagination.page, searchQuery, filterType]);

  const handleUploadComplete = () => {
    fetchTracks(); // Refresh tracks after upload
  };

  const handleDeleteTrack = async (trackId: string) => {
    if (!confirm('Are you sure you want to delete this track?')) return;

    try {
      setIsDeletingTrack(trackId);
      await apiService.deleteTrack(trackId);
      toast({
        title: 'Track deleted',
        description: 'The track has been deleted from your library.',
      });
      fetchTracks(); // Refresh tracks
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.response?.data?.error || 'Failed to delete track',
        variant: 'destructive',
      });
    } finally {
      setIsDeletingTrack(null);
    }
  };

  const handleEditTrack = (track: Track) => {
    setSelectedTrack(track);
    setIsEditDialogOpen(true);
  };

  const handleTrackUpdated = (updated: Track) => {
    setTracks(prev => prev.map(t => t.id === updated.id ? updated : t));
  };

  const toggleWaveform = (trackId: string) => {
    setExpandedWaveform(prev => prev === trackId ? null : trackId);
  };

  const handlePlayTrack = (track: Track) => {
    setPlayingTrackId(track.id);
    onTrackSelect?.(track);
    // TODO: Implement actual playback
    toast({
      title: 'Playing track',
      description: `Now playing: ${track.title} by ${track.artist}`,
    });
  };

  const formatDuration = (durationMs?: number): string => {
    if (!durationMs) return '0:00';
    const minutes = Math.floor(durationMs / 60000);
    const seconds = Math.floor((durationMs % 60000) / 1000);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', '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 (isLoading) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* En-tête avec contrôles */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center space-x-2">
                <Music className="h-6 w-6" />
                <span>Ma Bibliothèque</span>
              </CardTitle>
              <CardDescription>
                Gérez votre collection audio personnelle
              </CardDescription>
            </div>
            <Button onClick={() => setIsUploadModalOpen(true)}>
              <Upload className="h-4 w-4 mr-2" />
              Upload Track
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* Barre de recherche et filtres */}
          <div className="flex items-center space-x-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search in your library..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            <div className="flex items-center space-x-2">
              <Filter className="h-4 w-4" />
              <select
                value={filterType}
                onChange={(e) => setFilterType(e.target.value)}
                className="px-3 py-2 border rounded-md"
              >
                <option value="all">All</option>
                <option value="artist">By Artist</option>
                <option value="album">By Album</option>
                <option value="public">Public Only</option>
              </select>
            </div>
            <div className="flex items-center space-x-1">
              <Button
                variant={viewMode === 'grid' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('grid')}
              >
                <Grid className="h-4 w-4" />
              </Button>
              <Button
                variant={viewMode === 'list' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('list')}
              >
                <List className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tracks List */}
      {error && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-red-500">
              Error loading library: {error}
            </div>
          </CardContent>
        </Card>
      )}

      {tracks.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8">
              <FileAudio className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium mb-2">Empty Library</h3>
              <p className="text-muted-foreground mb-4">
                {searchQuery ? 'No tracks match your search.' : 'Start by uploading your first track.'}
              </p>
              {!searchQuery && (
                <Button onClick={() => setIsUploadModalOpen(true)}>
                  <Upload className="h-4 w-4 mr-2" />
                  Upload Track
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      ) : (
        <div 
          ref={parentRef}
          className="h-[600px] overflow-auto"
        >
          <VirtualLibraryGrid
            tracks={tracks}
            viewMode={viewMode}
            onTrackSelect={handlePlayTrack}
            onTrackDelete={handleDeleteTrack}
            onTrackEdit={handleEditTrack}
            isPlaying={(trackId) => playingTrackId === trackId}
            parentRef={parentRef}
          />
        </div>
      )}

      {/* Track Edit Dialog */}
      {selectedTrack && (
        <TrackEditDialog
          track={selectedTrack}
          open={isEditDialogOpen}
          onOpenChange={setIsEditDialogOpen}
          onTrackUpdated={handleTrackUpdated}
        />
      )}

      {/* Statistics */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div>
              <div className="text-2xl font-bold">{pagination.total}</div>
              <div className="text-sm text-muted-foreground">Total Tracks</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {tracks.filter(track => track.isPublic).length}
              </div>
              <div className="text-sm text-muted-foreground">Public Tracks</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {tracks.reduce((total, track) => total + (track.playCount || 0), 0)}
              </div>
              <div className="text-sm text-muted-foreground">Total Plays</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {Math.round(tracks.reduce((total, track) => total + (track.durationMs || 0), 0) / 60000)}m
              </div>
              <div className="text-sm text-muted-foreground">Total Duration</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Upload Modal - Centralisé (une seule instance) */}
      <UploadModal 
        isOpen={isUploadModalOpen}
        onClose={() => setIsUploadModalOpen(false)}
        onUploadComplete={() => {
          handleUploadComplete();
          setIsUploadModalOpen(false);
        }}
      />

      {/* Edit Dialog */}
      {selectedTrack && (
        <TrackEditDialog
          track={selectedTrack}
          isOpen={isEditDialogOpen}
          onClose={() => {
            setIsEditDialogOpen(false);
            setSelectedTrack(null);
          }}
          onTrackUpdated={handleTrackUpdated}
        />
      )}
    </div>
  );
}
