import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Music, Disc3 } from '../lib/icons'
import { useLibraryItems } from '../hooks/use-jellyfin'
import PosterCard from '../components/ui/PosterCard'
import { getBestImage, getStoredServerUrl } from '../api/jellyfin'

export default function MusicPage() {
  const navigate = useNavigate()
  const serverUrl = getStoredServerUrl()

  const { data: artists, isLoading: artistsLoading } = useLibraryItems(undefined, {
    includeItemTypes: ['MusicArtist'],
    sortBy: ['SortName'],
    sortOrder: ['Ascending'],
    limit: 100,
  })

  const { data: albums, isLoading: albumsLoading } = useLibraryItems(undefined, {
    includeItemTypes: ['MusicAlbum'],
    sortBy: ['SortName'],
    sortOrder: ['Ascending'],
    limit: 100,
  })

  return (
    <div className="px-7 pt-4 pb-12">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center gap-2 mb-1.5">
          <span className="w-1 h-3.5 rounded-full bg-accent" />
          <span className="text-[11px] font-semibold text-text-2 uppercase tracking-[0.14em]">Library</span>
        </div>
        <h1 className="text-3xl md:text-4xl font-bold font-display text-text-1 tracking-tight">Music</h1>
      </div>

      {/* Albums */}
      <Section title="Albums" icon={Disc3}>
        {albumsLoading ? (
          <SquareGridSkeleton count={14} />
        ) : !albums?.Items?.length ? (
          <EmptyState message="No albums" />
        ) : (
          <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 gap-4 gap-y-7">
            {albums.Items.map((item, i) => (
              <motion.div
                key={item.Id}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: Math.min(i * 0.015, 0.3), ease: [0.16, 1, 0.3, 1] }}
              >
                <PosterCard
                  item={item}
                  aspect="square"
                  priority={i < 12}
                  onClick={() => item.Id && navigate(`/item/${item.Id}`)}
                />
              </motion.div>
            ))}
          </div>
        )}
      </Section>

      {/* Artists */}
      <Section title="Artists" icon={Music}>
        {artistsLoading ? (
          <ArtistGridSkeleton />
        ) : !artists?.Items?.length ? (
          <EmptyState message="No artists" />
        ) : (
          <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 xl:grid-cols-8 2xl:grid-cols-10 gap-x-3 gap-y-5">
            {artists.Items.map((item, i) => {
              const imageUrl = getBestImage(serverUrl, item, 'primary', 240)

              return (
                <motion.button
                  key={item.Id}
                  onClick={() => item.Id && navigate(`/item/${item.Id}`)}
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3, delay: Math.min(i * 0.015, 0.3) }}
                  whileHover={{ y: -2 }}
                  className="flex flex-col items-center text-center gap-2 group focus-ring rounded-xl p-1"
                >
                  <div className="relative w-20 h-20 md:w-24 md:h-24">
                    <div className="absolute inset-0 rounded-full bg-accent/0 group-hover:bg-accent/15 blur-xl transition-all duration-300" />
                    <div className="relative w-full h-full rounded-full overflow-hidden bg-elevated ring-1 ring-border group-hover:ring-accent/40 transition-all duration-300">
                      {imageUrl ? (
                        <img
                          src={imageUrl}
                          alt={item.Name || ''}
                          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                          loading="lazy"
                        />
                      ) : (
                        <div className="w-full h-full grid place-items-center text-text-3 text-lg font-display font-semibold bg-gradient-to-br from-elevated to-surface">
                          {(item.Name || '?')[0].toUpperCase()}
                        </div>
                      )}
                    </div>
                  </div>
                  <span className="text-[12px] text-text-1 truncate w-full font-medium tracking-tight">{item.Name}</span>
                </motion.button>
              )
            })}
          </div>
        )}
      </Section>
    </div>
  )
}

function Section({
  title,
  icon: Icon,
  children,
}: {
  title: string
  icon: typeof Music
  children: React.ReactNode
}) {
  return (
    <section className="mb-10">
      <div className="flex items-center gap-2 mb-4">
        <Icon size={14} className="text-accent" strokeWidth={2} />
        <h2 className="text-[16px] font-semibold text-text-1 tracking-tight">{title}</h2>
      </div>
      {children}
    </section>
  )
}

function EmptyState({ message }: { message: string }) {
  return <p className="text-[12px] text-text-4">{message}</p>
}

function SquareGridSkeleton({ count }: { count: number }) {
  return (
    <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 gap-4 gap-y-7">
      {Array.from({ length: count }).map((_, i) => (
        <div key={i}>
          <div className="skeleton aspect-square rounded-lg" />
          <div className="mt-2 space-y-1">
            <div className="skeleton h-3 w-3/4 rounded" />
            <div className="skeleton h-2.5 w-1/2 rounded" />
          </div>
        </div>
      ))}
    </div>
  )
}

function ArtistGridSkeleton() {
  return (
    <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 xl:grid-cols-8 2xl:grid-cols-10 gap-x-3 gap-y-5">
      {Array.from({ length: 12 }).map((_, i) => (
        <div key={i} className="flex flex-col items-center">
          <div className="skeleton w-20 h-20 md:w-24 md:h-24 rounded-full" />
          <div className="skeleton h-3 w-16 mt-2 rounded" />
        </div>
      ))}
    </div>
  )
}
