import { useQuery } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router';
import { Zap, Music, Disc3, Users } 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 { usePlaybackStore } from '../store/usePlaybackStore';
import type { HistoryEntry, Track } from '../types';

const SHORTCUTS = [
  { label: 'Songs', icon: Music, to: '/tracks' as const },
  { label: 'Albums', icon: Disc3, to: '/albums' as const },
  { label: 'Artists', icon: Users, to: '/artists' as const },
];

/** 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 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">
      <div className="animate-rise">
        <h1 className="text-gradient text-4xl font-extrabold tracking-tight">Good listening</h1>
        <p className="text-muted mt-1.5">Your music, your way.</p>
      </div>

      {/* Vibe hero + quick shortcuts */}
      <section className="grid gap-3 sm:grid-cols-[2fr_3fr]">
        <Link
          to="/vibe"
          className="group relative overflow-hidden rounded-2xl border border-accent/30 bg-gradient-to-br from-accent/30 to-accent/5 p-5 flex flex-col justify-between min-h-[7rem] transition-all hover:-translate-y-0.5 hover:shadow-xl hover:shadow-accent/10"
        >
          <Zap size={22} className="text-accent transition-transform group-hover:scale-110" />
          <div>
            <div className="text-lg font-bold text-text">Start a Vibe</div>
            <div className="text-xs text-muted">Endless recommendations from your library.</div>
          </div>
        </Link>
        <div className="grid grid-cols-3 gap-3">
          {SHORTCUTS.map(({ label, icon: Icon, to }) => (
            <Link
              key={to}
              to={to}
              className="group flex flex-col items-center justify-center gap-2 rounded-2xl border border-border/70 bg-surface0/60 p-4 transition-all hover:-translate-y-0.5 hover:border-accent/40 hover:bg-surface1"
            >
              <Icon size={22} className="text-muted transition-colors group-hover:text-accent" />
              <span className="text-sm font-semibold text-text">{label}</span>
            </Link>
          ))}
        </div>
      </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>
  );
}
