import { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router';
import { Users, AlertCircle } from 'lucide-react';
import { artistService } from '../services/artistService';
import { Artwork } from '../components/Artwork';
import { PageContainer } from '../components/PageContainer';
import { PageHeader } from '../components/PageHeader';
import { Pagination } from '../components/Pagination';
import { EmptyState } from '../components/EmptyState';
import { SkeletonGrid } from '../components/LoadingState';
import type { Artist } from '../types';

const PAGE_SIZE = 50;

export default function Artists() {
  const [page, setPage] = useState(0);
  const { data, isLoading, isError, isPlaceholderData } = useQuery<Artist[]>({
    queryKey: ['artists', page],
    queryFn: () => artistService.listArtists({ limit: PAGE_SIZE, offset: page * PAGE_SIZE }),
    placeholderData: keepPreviousData,
  });
  const artists = data ?? [];
  const hasNext = artists.length === PAGE_SIZE;

  return (
    <PageContainer>
      <PageHeader
        title="Artists"
        meta={artists.length ? `${artists.length} shown · page ${page + 1}` : undefined}
      />
      {isLoading ? <SkeletonGrid count={10} />
        : isError ? <EmptyState compact icon={<AlertCircle size={28} />} title="Couldn't load artists" subtitle="Something went wrong. Try reloading the page." />
        : !artists?.length ? <EmptyState compact icon={<Users size={28} />} title="No artists yet" subtitle="Run a library scan in Settings to populate it." />
        : (
          <>
            <div className="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
              {artists.map((artist) => (
                <Link key={artist.id} to="/artists/$artistId" params={{ artistId: artist.id }}
                  className="card-surface group items-center p-2">
                  <div className="aspect-square w-full overflow-hidden rounded-full ring-1 ring-border transition-all group-hover:ring-accent/40">
                    <Artwork seed={artist.name} src={artist.image_path} className="w-full h-full transition-transform duration-500 group-hover:scale-105" rounded="full" />
                  </div>
                  <div className="w-full truncate text-center text-xs font-medium text-text transition-colors group-hover:text-accent" title={artist.name}>{artist.name}</div>
                </Link>
              ))}
            </div>
            <Pagination
              page={page}
              hasNext={hasNext}
              isLoading={isPlaceholderData}
              onPrev={() => setPage((p) => Math.max(0, p - 1))}
              onNext={() => setPage((p) => p + 1)}
            />
          </>
        )}
    </PageContainer>
  );
}
