import { db } from "@/lib/db";
import { videos, categories } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { auth } from "@/lib/auth";
import { TierBadge } from "@/components/VideoCard";
import VideoPlayer from "@/components/VideoPlayer";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getSetting } from "@/lib/settings";
import PartnersInMission from "@/components/PartnersInMission";

export const dynamic = "force-dynamic";

const TIER_RANK: Record<string, number> = { free: 0, starter: 1, plus: 2, premium: 3 };

export default async function VideoPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const video = (await db.select().from(videos).where(eq(videos.slug, slug)))[0];
  if (!video) return notFound();

  const session = await auth();
  const userTier = (session?.user as any)?.tier || "free";
  const userRole = (session?.user as any)?.role;

  let hasAccess = false;
  if (video.accessTier === "free") hasAccess = true;
  else if (video.accessTier === "ppv") hasAccess = false; // would check purchase table in a full build
  else hasAccess = TIER_RANK[userTier] >= TIER_RANK[video.accessTier];
  if (userRole === "admin") hasAccess = true;

  // Preview limit: if this video isn't fully accessible, but the admin has set a
  // preview length (per-video or a global default), a logged-out/insufficient-tier
  // visitor gets to watch that many seconds before being stopped.
  const globalPreview = parseInt(await getSetting("defaultPreviewSeconds", "0"), 10);
  const previewSeconds = video.previewSeconds ?? (globalPreview > 0 ? globalPreview : null);
  const showPreview = !hasAccess && !!previewSeconds;

  return (
    <div className="max-w-6xl mx-auto flex flex-col lg:flex-row gap-6 items-start">
      <div className="flex-1 min-w-0">
        <div className="relative aspect-video rounded-lg overflow-hidden bg-black mb-4">
          {hasAccess || showPreview ? (
            <VideoPlayer
              youtubeId={video.youtubeId}
              videoId={video.id}
              previewSeconds={hasAccess ? null : previewSeconds}
            />
          ) : (
            <div className="w-full h-full flex flex-col items-center justify-center gap-3 text-center p-6">
              <img
                src={`https://img.youtube.com/vi/${video.youtubeId}/hqdefault.jpg`}
                className="absolute inset-0 w-full h-full object-cover opacity-20"
              />
              <div className="relative z-10">
                <p className="font-semibold mb-2">
                  This video requires {video.accessTier === "ppv" ? `a one-time purchase ($${video.price?.toFixed(2)})` : `${video.accessTier} membership or higher`}.
                </p>
                <Link href="/subscription/plans" className="btn-primary px-5 py-2.5">
                  {video.accessTier === "ppv" ? "Purchase Access" : "Upgrade Membership"}
                </Link>
              </div>
            </div>
          )}
        </div>
        <div className="flex items-center gap-2 mb-2">
          <TierBadge tier={video.accessTier} price={video.price} inline />
          {showPreview && (
            <span className="text-xs bg-neutral-800 text-neutral-300 px-2.5 py-1 rounded-full">
              {previewSeconds}s free preview
            </span>
          )}
        </div>
        <h1 className="text-2xl font-bold mb-2">{video.title}</h1>
        <p className="text-neutral-500 text-sm mb-4">GraceMembership · {video.views} views</p>
        <p className="text-neutral-300">{video.description}</p>
      </div>

      {/* Right sidebar: scrolling Supporters / Partners in Mission */}
      <aside className="w-full lg:w-72 shrink-0">
        <PartnersInMission />
      </aside>
    </div>
  );
}
