import { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { Music, AlertCircle } from 'lucide-react';
import { trackService } from '../services/trackService';
import { TrackRow } from '../components/TrackRow';
import { PageHeader } from '../components/PageHeader';
import { PageContainer } from '../components/PageContainer';
import { Pagination } from '../components/Pagination';
import { EmptyState } from '../components/EmptyState';
import { SkeletonRows } from '../components/LoadingState';
import type { Track } from '../types';

const PAGE_SIZE = 50;

export default function Tracks() {
  const [page, setPage] = useState(0);
  const { data, isLoading, isError, isPlaceholderData } = useQuery<Track[]>({
    queryKey: ['tracks', page],
    queryFn: () => trackService.listTracks({ limit: PAGE_SIZE, offset: page * PAGE_SIZE, sort_by: 'title', order: 'ASC' }),
    placeholderData: keepPreviousData,
  });
  const tracks = data ?? [];
  const hasNext = tracks.length === PAGE_SIZE;

  return (
    <PageContainer>
      <PageHeader
        title="Songs"
        meta={tracks.length ? `${tracks.length} shown · page ${page + 1}` : undefined}
      />
      {isLoading ? <SkeletonRows count={8} />
        : isError ? <EmptyState compact icon={<AlertCircle size={28} />} title="Couldn't load tracks" subtitle="Something went wrong. Try reloading the page." />
        : tracks.length === 0 ? <EmptyState compact icon={<Music size={28} />} title={page === 0 ? 'No tracks yet' : 'No more tracks'} subtitle={page === 0 ? 'Run a library scan in Settings to populate it.' : undefined} />
        : <div className="track-list">{tracks.map((t, i) => <TrackRow key={t.id} track={t} queue={tracks} index={i} />)}</div>}
      {(tracks.length > 0 || page > 0) && (
        <Pagination
          page={page}
          hasNext={hasNext}
          isLoading={isPlaceholderData}
          onPrev={() => setPage((p) => Math.max(0, p - 1))}
          onNext={() => setPage((p) => p + 1)}
        />
      )}
    </PageContainer>
  );
}
