import { useState, useEffect } 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 { UploadModal } from './UploadModal';
// import { TrackEditDialog } from '@/features/tracks/components/TrackEditDialog';
import { TrackGrid } from '@/features/tracks/components/TrackGrid';
import { TrackList } from '@/features/tracks/components/TrackList';
import { apiClient } from '@/services/api/client';
import type { Track as ApiTrack } from '@/features/tracks/types/track';
import type { Track as PlayerTrack } from '@/features/player/types';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  Music,
  Upload,
  Search,
  Filter,
  Grid,
  List,
  FileAudio,
} from 'lucide-react';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';

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

export function LibraryManager({ onTrackSelect }: LibraryManagerProps) {
  const [tracks, setTracks] = useState<ApiTrack[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = 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 [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [playingTrackId, setPlayingTrackId] = useState<string | null>(null);
  const { info: showInfo } = useToast();

  const fetchTracks = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await apiClient.get<{
        data: ApiTrack[];
        total: number;
        page: number;
        limit: number;
      }>('/tracks', {
        params: {
          page: pagination.page,
          limit: pagination.limit,
          search: searchQuery || undefined,
          artist: filterType !== 'all' ? filterType : undefined,
        },
      });
      // apiClient unwrap déjà le format { success, data }
      const data = response.data;
      setTracks(data.data || []);
      setPagination((prev) => ({
        ...prev,
        total: data.total || 0,
      }));
    } catch (err: unknown) {
      const apiError = parseApiError(err);
      setError(apiError.message);
      logger.error('Error fetching tracks:', { message: apiError.message });
    } finally {
      setIsLoading(false);
    }
  };

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

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

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

    try {
      await apiClient.delete(`/tracks/${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',
      });
    }
  };
  */

  const handleEditTrack = (track: PlayerTrack) => {
    // Need mapping back to ApiTrack if needed, or just find it
    const originalTrack = tracks.find((t) => t.id === track.id);
    if (originalTrack) {
      // setSelectedTrack(originalTrack);
      // setIsEditDialogOpen(true);
      // TODO: Implement edit track functionality
    }
  };

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

  const handlePlayTrack = (track: PlayerTrack) => {
    setPlayingTrackId(track.id);
    // onTrackSelect expected ApiTrack
    const originalTrack = tracks.find((t) => t.id === track.id);
    if (originalTrack) {
      onTrackSelect?.(originalTrack);
      showInfo(`Now playing: ${track.title} by ${track.artist}`);
    }
  };

  const mapToPlayerTrack = (track: ApiTrack): PlayerTrack => ({
    id: track.id,
    title: track.title,
    artist: track.artist,
    album: track.album,
    duration: track.duration,
    url: track.stream_manifest_url || track.file_path, // Fallback
    cover: track.cover_art_path,
    genre: track.genre,
  });

  const playerTracks = tracks.map(mapToPlayerTrack);

  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 className="h-[600px] overflow-auto">
          {viewMode === 'grid' ? (
            <TrackGrid
              tracks={playerTracks}
              onTrackClick={handlePlayTrack} // Clicking card plays needed? Or selects?
              onTrackPlay={handlePlayTrack}
              isLiked={() => false} // Todo
              isPlaying={(id) => id === playingTrackId}
              onTrackMore={handleEditTrack}
            />
          ) : (
            <TrackList
              tracks={playerTracks}
              onTrackClick={handlePlayTrack}
              onTrackPlay={handlePlayTrack}
              onTrackMore={handleEditTrack}
              isLiked={() => false}
              currentPlayingId={playingTrackId}
            />
          )}
        </div>
      )}

      {/* 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.is_public).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.play_count || 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.duration || 0),
                    0,
                  ) / 60,
                )}
                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 - Commented out as missing */}
      {/* {selectedTrack && (
        <TrackEditDialog
          track={selectedTrack}
          isOpen={isEditDialogOpen}
          onClose={() => {
            setIsEditDialogOpen(false);
            setSelectedTrack(null);
          }}
          onTrackUpdated={handleTrackUpdated}
        />
      )} */}
    </div>
  );
}
