import { db } from "@/lib/db";
import { playlists, playlistItems } from "@/lib/db/schema";
import { eq, desc } from "drizzle-orm";

export const dynamic = "force-dynamic";

function PlaylistCard({ pl }: { pl: any }) {
  return (
    <div className="card overflow-hidden hover:border-neutral-600 transition-colors">
      <div className="aspect-video bg-neutral-800 flex items-center justify-center relative">
        {pl.coverUrl ? (
          <img src={pl.coverUrl} className="w-full h-full object-cover" />
        ) : (
          <span className="text-3xl opacity-30">📃</span>
        )}
        <span className="absolute bottom-2 right-2 bg-black/70 text-xs px-2 py-0.5 rounded-full">
          {pl.count} videos
        </span>
      </div>
      <div className="p-3">
        <h3 className="font-semibold text-sm line-clamp-2">{pl.title}</h3>
      </div>
    </div>
  );
}

export default async function PlaylistsPage() {
  const lists = await db.select().from(playlists).orderBy(desc(playlists.createdAt));

  const listsWithCounts = await Promise.all(
    lists.map(async (pl) => {
      const items = await db.select().from(playlistItems).where(eq(playlistItems.playlistId, pl.id));
      return { ...pl, count: items.length };
    })
  );

  // "Popular" = most videos in the playlist (best available proxy — no dedicated
  // playlist-view counter yet). "Latest" = most recently created.
  const popular = [...listsWithCounts].sort((a, b) => b.count - a.count).slice(0, 8);
  const latest = [...listsWithCounts].slice(0, 8);

  return (
    <div className="max-w-7xl mx-auto">
      <h1 className="text-2xl font-bold mb-1">Playlists</h1>
      <p className="text-neutral-400 text-sm mb-6">Curated collections of devotional content</p>

      {listsWithCounts.length === 0 ? (
        <p className="text-neutral-500">No playlists yet — add some from the admin panel.</p>
      ) : (
        <>
          <section className="mb-10">
            <h2 className="text-lg font-bold mb-4">Popular Playlists</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
              {popular.map((pl) => <PlaylistCard key={pl.id} pl={pl} />)}
            </div>
          </section>

          <section>
            <h2 className="text-lg font-bold mb-4">Latest Playlists</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
              {latest.map((pl) => <PlaylistCard key={pl.id} pl={pl} />)}
            </div>
          </section>
        </>
      )}
    </div>
  );
}
