import { Link } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Plus, Music } from 'lucide-react';
import { usePlaylists, PLAYLISTS_KEYS } from '../hooks/usePlaylists';
import { CreatePlaylistDialog } from '../components/CreatePlaylistDialog';
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';

export default function PlaylistsPage() {
  const { data, isLoading } = usePlaylists();
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const queryClient = useQueryClient();

  const handleCreated = () => {
    queryClient.invalidateQueries({ queryKey: PLAYLISTS_KEYS.lists() });
  };

  if (isLoading) {
    return <div>Chargement...</div>;
  }

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold tracking-tight">Mes Playlists</h1>
        <Button onClick={() => setIsCreateOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          Nouvelle Playlist
        </Button>
      </div>

      <CreatePlaylistDialog
        open={isCreateOpen}
        onOpenChange={setIsCreateOpen}
        onCreated={handleCreated}
      />

      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {data?.playlists.map((playlist) => (
          <Link key={playlist.id} to={`/playlists/${playlist.id}`}>
            <Card className="h-full hover:shadow-md transition-shadow cursor-pointer">
              <div className="aspect-square bg-muted relative">
                {playlist.cover_url ? (
                  <img src={playlist.cover_url} alt={playlist.title} className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center bg-muted">
                    <Music className="h-12 w-12 text-muted-foreground" />
                  </div>
                )}
              </div>
              <CardHeader>
                <CardTitle className="truncate">{playlist.title}</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">{playlist.track_count} titres</p>
                <p className="text-sm text-muted-foreground truncate">{playlist.description}</p>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
