import { useQuery } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router';
import { Zap } from 'lucide-react';
import { ShelfRow } from '../components/ShelfRow';
import { MediaCard } from '../components/MediaCard';
import { PageContainer } from '../components/PageContainer';
import { Skeleton } from '../components/LoadingState';
import { historyService } from '../services/historyService';
import { trackService } from '../services/trackService';
import { fetchLibraryStats, type LibraryStats } from '../services/libraryService';
import { usePlaybackStore } from '../store/usePlaybackStore';
import type { HistoryEntry, Track } from '../types';

/** `128h 04m` — total library playtime, sized to read at a glance. */
function formatTotalTime(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${hours.toLocaleString()}h ${minutes.toString().padStart(2, '0')}m`;
}

/** A row of placeholder cards matching MediaCard's shelf width. */
function ShelfSkeleton({ count = 6 }: { count?: number }) {
  return (
    <div className="flex gap-4 pb-2">
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} className="w-36 shrink-0">
          <Skeleton className="aspect-square rounded-xl" />
          <Skeleton className="mt-2 h-3 w-3/4" />
          <Skeleton className="mt-1.5 h-2.5 w-1/2" />
        </div>
      ))}
    </div>
  );
}

export default function Home() {
  const { setQueue, playTrack } = usePlaybackStore();

  const history = useQuery<HistoryEntry[]>({
    queryKey: ['history'],
    queryFn: () => historyService.list(),
  });

  const mostPlayed = useQuery<Track[]>({
    queryKey: ['most-played'],
    queryFn: () => trackService.listTracks({ limit: 12, sort_by: 'play_count', order: 'DESC' }),
  });

  const stats = useQuery<LibraryStats>({
    queryKey: ['library-stats'],
    queryFn: fetchLibraryStats,
    staleTime: 60_000,
  });

  const counts = stats.data
    ? `${stats.data.tracks.toLocaleString()} tracks · ${stats.data.albums.toLocaleString()} albums · ` +
      `${stats.data.artists.toLocaleString()} artists · ${formatTotalTime(stats.data.duration)}`
    : null;

  const playFrom = (list: Track[], index: number) => {
    setQueue(list.slice(index));
    playTrack(list[index]);
  };

  const historyTracks: Track[] = (history.data ?? []).slice(0, 12);

  return (
    <PageContainer width="lg" className="space-y-8">
      {/* Vibe hero. The three library shortcuts that used to sit beside it were
          duplicates of the nav rail two inches to the left — the space now goes
          to the one action this page is for, plus what the library actually holds. */}
      <section className="animate-rise flex flex-wrap items-end justify-between gap-4 border-b border-border pb-4">
        <div className="min-w-0">
          <h1 className="text-3xl font-semibold tracking-tight text-text sm:text-4xl">Good listening</h1>
          <p className="mt-1.5 font-mono text-xs tabular-nums text-machine">
            {counts ?? 'reading library…'}
          </p>
        </div>
        <Link
          to="/vibe"
          className="group flex flex-none items-center gap-2.5 rounded-lg border border-accent/40 bg-accent/10 px-4 py-2.5 text-sm font-medium text-accent transition-colors hover:bg-accent/20"
        >
          <Zap size={18} className="transition-transform group-hover:scale-110" />
          Start a Vibe
        </Link>
      </section>

      <ShelfRow title="Continue Listening" viewAllTo="/tracks">
        {history.isLoading ? (
          <ShelfSkeleton />
        ) : historyTracks.length === 0 ? (
          <p className="text-sm text-muted py-4">Nothing played yet.</p>
        ) : (
          historyTracks.map((track, i) => (
            <div key={`${track.id}-${i}`} className="w-36 shrink-0">
              <MediaCard
                seed={`${track.title} ${track.artist}`}
                title={track.title}
                subtitle={track.artist}
                artSrc={track.artwork_id}
                onClick={() => playFrom(historyTracks, i)}
              />
            </div>
          ))
        )}
      </ShelfRow>

      <ShelfRow title="Most Played" viewAllTo="/tracks">
        {mostPlayed.isLoading ? (
          <ShelfSkeleton />
        ) : (mostPlayed.data ?? []).length === 0 ? (
          <p className="text-sm text-muted py-4">No tracks yet.</p>
        ) : (
          (mostPlayed.data ?? []).map((track, i) => (
            <div key={track.id} className="w-36 shrink-0">
              <MediaCard
                seed={`${track.title} ${track.artist}`}
                title={track.title}
                subtitle={`${track.play_count} plays`}
                artSrc={track.artwork_id}
                onClick={() => playFrom(mostPlayed.data!, i)}
              />
            </div>
          ))
        )}
      </ShelfRow>
    </PageContainer>
  );
}
