import { useQuery } from '@tanstack/react-query';
import { Play, AlertCircle, Music } from 'lucide-react';
import { albumDetailRoute } from '../router';
import { albumService } from '../services/albumService';
import { usePlaybackStore } from '../store/usePlaybackStore';
import { Artwork } from '../components/Artwork';
import { TrackRow } from '../components/TrackRow';
import { ArtistLinks } from '../components/ArtistLinks';
import { BackLink } from '../components/BackLink';
import { Button } from '../components/ethos/Button';
import { PageContainer } from '../components/PageContainer';
import { EmptyState } from '../components/EmptyState';
import { LoadingState } from '../components/LoadingState';
import type { AlbumWithTracks } from '../types';

export default function AlbumDetail() {
  const { albumId } = albumDetailRoute.useParams();
  const { setQueue, playTrack } = usePlaybackStore();
  const { data, isLoading, isError } = useQuery<AlbumWithTracks>({
    queryKey: ['album', albumId],
    queryFn: () => albumService.getAlbum(albumId),
  });
  if (isLoading) return <LoadingState className="py-20" />;
  if (isError || !data) return <EmptyState icon={<AlertCircle size={28} />} title="Couldn't load album" subtitle="Something went wrong. Try reloading the page." />;
  // Tracks inherit the album's artwork when they lack their own — this is the
  // most common case since artwork is stored at the album level, not per-track.
  const tracks = (data.tracks ?? []).map((t) => ({
    ...t,
    artwork_id: t.artwork_id || data.artwork_id,
  }));

  // Distinct artists across the album's tracks. The album's primary artist
  // (artist_id) comes first, then remaining mains, then featured guests.
  const artistMap = new Map<string, { id: string; name: string; role: 'main' | 'featured' }>();
  for (const t of tracks) {
    for (const a of t.artists ?? []) {
      const existing = artistMap.get(a.id);
      // Prefer 'main' if seen in any role.
      if (!existing || (existing.role === 'featured' && a.role === 'main')) {
        artistMap.set(a.id, { id: a.id, name: a.name, role: a.role });
      }
    }
  }
  const artists = [...artistMap.values()].sort((x, y) => {
    const rank = (a: typeof x) => (a.id === data.artist_id ? 0 : a.role === 'main' ? 1 : 2);
    return rank(x) - rank(y);
  });
  return (
    <PageContainer className="space-y-6">
      <BackLink to="/albums" label="Albums" />
      <div className="flex items-end gap-4 border-b border-border pb-4">
        <div className="h-28 w-28 flex-none overflow-hidden rounded-lg sm:h-32 sm:w-32">
          <Artwork seed={data.title} src={data.artwork_id} className="w-full h-full" rounded="lg" eager />
        </div>
        <div className="min-w-0 space-y-1.5">
          <h1 className="truncate text-2xl font-semibold tracking-tight text-text sm:text-3xl">{data.title}</h1>
          {artists.length > 0 && (
            <ArtistLinks
              artists={artists}
              fallback="Unknown artist"
              className="flex flex-wrap items-center gap-x-1 gap-y-0.5 text-sm"
            />
          )}
          <p className="font-mono text-xs tabular-nums text-machine">{data.year ? `${data.year} · ` : ''}{tracks.length} tracks</p>
          <Button
            variant="primary"
            icon={<Play size={16} fill="currentColor" />}
            onClick={() => { if (tracks.length) { setQueue(tracks); playTrack(tracks[0]); } }}
            disabled={!tracks.length}
          >
            Play album
          </Button>
        </div>
      </div>
      <section className="track-list">
        {tracks.length === 0 ? <EmptyState compact icon={<Music size={28} />} title="No tracks in this album" />
          : tracks.map((t, i) => <TrackRow key={t.id} track={t} queue={tracks} index={i} />)}
      </section>
    </PageContainer>
  );
}
