import { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router';
import { Disc3, AlertCircle } from 'lucide-react';
import { albumService } from '../services/albumService';
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 { Album } from '../types';

const PAGE_SIZE = 50;

export default function Albums() {
  const [page, setPage] = useState(0);
  const { data, isLoading, isError, isPlaceholderData } = useQuery<Album[]>({
    queryKey: ['albums', page],
    queryFn: () => albumService.listAlbums({ limit: PAGE_SIZE, offset: page * PAGE_SIZE }),
    placeholderData: keepPreviousData,
  });
  const albums = data ?? [];
  const hasNext = albums.length === PAGE_SIZE;

  return (
    <PageContainer>
      <PageHeader
        title="Albums"
        meta={albums.length ? `${albums.length} shown · page ${page + 1}` : undefined}
      />
      {isLoading ? <SkeletonGrid count={10} />
        : isError ? <EmptyState compact icon={<AlertCircle size={28} />} title="Couldn't load albums" subtitle="Something went wrong. Try reloading the page." />
        : !albums?.length ? <EmptyState compact icon={<Disc3 size={28} />} title="No albums yet" subtitle="Run a library scan in Settings to populate it." />
        : (
          <>
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
              {albums.map((album) => (
                <Link key={album.id} to="/albums/$albumId" params={{ albumId: album.id }}
                  className="card-surface group">
                  <div className="artwork-frame">
                    <Artwork seed={album.title} src={album.artwork_id} className="w-full h-full transition-transform duration-500 group-hover:scale-105" rounded="lg" />
                  </div>
                  <div>
                    <div className="truncate text-sm font-medium text-text" title={album.title}>{album.title}</div>
                    <div className="mt-0.5 flex items-baseline gap-1.5 text-xs">
                      <span className="truncate text-secondary">{album.artist_name || 'Unknown artist'}</span>
                      {album.year && <span className="flex-none font-mono tabular-nums text-machine">{album.year}</span>}
                    </div>
                  </div>
                </Link>
              ))}
            </div>
            <Pagination
              page={page}
              hasNext={hasNext}
              isLoading={isPlaceholderData}
              onPrev={() => setPage((p) => Math.max(0, p - 1))}
              onNext={() => setPage((p) => p + 1)}
            />
          </>
        )}
    </PageContainer>
  );
}
