import { HomeFeed } from "@/components/home-feed";
import { getHistory, listVideos } from "@/lib/data";
import { getSessionUser } from "@/lib/auth";
import { ensureSeeded } from "@/lib/seed";
import { db } from "@/db";
import { sql } from "drizzle-orm";

export const dynamic = "force-dynamic";

export default async function HomePage({ searchParams }: { searchParams: Promise<{ category?: string }> }) {
  await ensureSeeded();
  const { category } = await searchParams;
  const session = await getSessionUser();
  const [items, history] = await Promise.all([
    listVideos({ category, sort: "recommended", limit: 12, subscriberOfUserId: undefined }),
    session ? getHistory(session.user.id, 10) : Promise.resolve([]),
  ]);
  const [stats] = (await db.execute<{ videos: string; channels: string }>(sql`
    SELECT (SELECT count(*) FROM videos)::text AS videos, (SELECT count(*) FROM channels)::text AS channels
  `)).rows;

  return (
    <div className="px-4 pt-4">
      <section className="mb-6 overflow-hidden rounded-2xl border border-line bg-gradient-to-br from-brand/20 via-surface to-surface p-5 sm:p-8">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="max-w-xl">
            <h1 className="text-2xl font-bold sm:text-3xl">Watch, upload and go live on PlayTube</h1>
            <p className="mt-2 text-sm text-muted">
              Adaptive HLS streaming, shorts, live chat, playlists, creator analytics and monetization — all in one
              installable app.
            </p>
          </div>
          <div className="flex gap-4 text-center text-sm">
            <div>
              <p className="text-2xl font-bold text-brand">{Number(stats?.videos ?? 0)}</p>
              <p className="text-xs text-muted">videos</p>
            </div>
            <div>
              <p className="text-2xl font-bold text-brand">{Number(stats?.channels ?? 0)}</p>
              <p className="text-xs text-muted">channels</p>
            </div>
          </div>
        </div>
      </section>
      <HomeFeed initialItems={items} initialCategory={category} continueWatching={history.filter((h) => (h.progressSeconds ?? 0) > 5)} />
    </div>
  );
}
