export const dynamic = "force-dynamic";

import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { LayoutGrid, ChevronLeft, ChevronRight, Sparkles, Flame, Clock } from "lucide-react";
import { TrendingCarousel } from "@/components/TrendingCarousel";
import { VideoCard } from "@/components/VideoCard";
import { PersonalizedFeed } from "@/components/PersonalizedFeed";
import { formatNumber } from "@/lib/utils";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

const PER_PAGE = 32;

export default async function HomePage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; cat?: string; tab?: string }>;
}) {
  const cookieStore = await cookies();
  const bypass = cookieStore.get('bypass_maintenance')?.value;
  // Change to true to enable maintenance mode for the homepage
  const IS_MAINTENANCE_MODE = false; 
  if (IS_MAINTENANCE_MODE && bypass !== 'Decelle01') {
    redirect('/maintenance');
  }

  const { page: pageParam, cat, tab = "foryou" } = await searchParams;
  const page = Math.max(1, parseInt(pageParam || "1"));

  const showForYou = tab === "foryou" && !cat;
  
  const where: any = { type: "VIDEO", isPublished: true };
  if (cat) where.categoryId = cat;

  // Use a random skip to make the "Tendances" section feel fresh
  const randomSkip = Math.floor(Math.random() * 5000);

  const [trendingVideos, allCategories, videos, latestVideos] = await Promise.all([
    page === 1
      ? prisma.media.findMany({
          where: { type: "VIDEO", isPublished: true },
          orderBy: { id: "desc" },
          take: 5,
          include: { uploader: true },
        })
      : Promise.resolve([]),
    prisma.category.findMany({
      where: { media: { some: { isPublished: true } } },
      take: 60,
      select: { id: true, name: true, slug: true },
    }),
    !showForYou
      ? prisma.media.findMany({
          where,
          orderBy: { id: "desc" },
          skip: (page - 1) * PER_PAGE,
          take: PER_PAGE,
          include: { uploader: true, category: true },
        })
      : Promise.resolve([]),
    // Section Tendances — 8 vidéos très populaires
    page === 1 && showForYou
      ? prisma.media.findMany({
          where: { type: "VIDEO", isPublished: true },
          orderBy: { views: "desc" },
          skip: randomSkip,
          take: 8,
          include: { category: true },
        })
      : Promise.resolve([]),
  ]);

  const total = 10000; // Faux total pour pagination ultra rapide (évite un count() de 8 secondes)

  const totalPages = Math.ceil(total / PER_PAGE);
  const isCleanName = (name: string) => !/^[\d°\s.\-/°]+$/.test(name) && name.length > 2;
  const topCategories = allCategories.filter((c) => isCleanName(c.name)).slice(0, 18);

  const buildUrl = (p: number) => {
    const sp = new URLSearchParams();
    if (cat) sp.set("cat", cat);
    if (tab && tab !== "foryou") sp.set("tab", tab);
    sp.set("page", String(p));
    return `/?${sp.toString()}`;
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">

      {/* Categories Bar — Pill style */}
      <div className="flex gap-2 overflow-x-auto pb-3 mb-8 scrollbar-hide">
        <Link
          href="/?tab=foryou"
          className={`flex-shrink-0 flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-bold transition-all ${
            showForYou
              ? "bg-[#b57bee] text-black shadow-[0_0_20px_rgba(181,123,238,0.4)]"
              : "bg-[#14141f] border border-[#2a2a40] text-[#9d9db8] hover:border-[#b57bee]/40 hover:text-white"
          }`}
        >
          <Sparkles size={13} /> Pour Vous
        </Link>
        <Link
          href="/?tab=all"
          className={`flex-shrink-0 flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-bold transition-all ${
            tab === "all" && !cat
              ? "bg-[#b57bee] text-black shadow-[0_0_20px_rgba(181,123,238,0.4)]"
              : "bg-[#14141f] border border-[#2a2a40] text-[#9d9db8] hover:border-[#b57bee]/40 hover:text-white"
          }`}
        >
          Toutes les vidéos
        </Link>
        <div className="w-px h-7 bg-[#2a2a40] mx-1 self-center flex-shrink-0" />
        {topCategories.map((c) => (
          <Link
            key={c.id}
            href={`/?cat=${c.id}`}
            className={`flex-shrink-0 px-4 py-2 rounded-full text-sm font-semibold transition-all ${
              cat === c.id
                ? "bg-[#b57bee] text-black shadow-[0_0_20px_rgba(181,123,238,0.4)]"
                : "bg-[#14141f] border border-[#2a2a40] text-[#9d9db8] hover:border-[#b57bee]/40 hover:text-white"
            }`}
          >
            {c.name}
          </Link>
        ))}
        <Link
          href="/categories"
          className="flex-shrink-0 flex items-center gap-1 px-4 py-2 rounded-full text-sm font-semibold bg-[#14141f] border border-[#b57bee]/30 text-[#b57bee] hover:bg-[#b57bee]/10 transition-all"
        >
          <LayoutGrid size={12} /> Tout voir
        </Link>
      </div>

      {/* Trending — page 1 seulement */}
      {page === 1 && trendingVideos.length > 0 && <TrendingCarousel videos={trendingVideos} />}

      {showForYou ? (
        <>
          {/* Section Tendances */}
          {latestVideos.length > 0 && (
            <div className="mb-12">
              <div className="flex items-center justify-between mb-5">
                <h2 className="text-lg font-black flex items-center gap-2">
                  <span className="flex items-center justify-center w-7 h-7 rounded-lg bg-[#b57bee]/15 border border-[#b57bee]/25">
                    <Flame size={14} className="text-[#b57bee]" />
                  </span>
                  Tendances
                </h2>
                <Link href="/?tab=all" className="text-xs text-[#b57bee] hover:text-[#c992f5] font-bold transition-colors">
                  Voir tout →
                </Link>
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-x-3 gap-y-7">
                {latestVideos.map((media) => (
                  <VideoCard key={media.id} media={media} />
                ))}
              </div>
              <div className="mt-10 mb-2 h-px bg-gradient-to-r from-transparent via-[#2a2a40] to-transparent" />
            </div>
          )}
          <PersonalizedFeed />
        </>
      ) : (
        <>
          {/* Header */}
          <div className="flex items-center justify-between mb-5">
            <p className="text-[#9d9db8] text-sm">
              <span className="text-white font-bold">{formatNumber(total)}</span> vidéos
              {totalPages > 1 && (
                <span className="ml-2 text-[#5f5f7a]">· Page {page}/{totalPages}</span>
              )}
            </p>
          </div>

          {/* Grid */}
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-x-3 gap-y-7 mb-10">
            {videos.map((media) => (
              <VideoCard key={media.id} media={media} />
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-4 pt-4 pb-8 border-t border-[#2a2a40]">
              {page > 1 ? (
                <Link
                  href={buildUrl(page - 1)}
                  className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#14141f] border border-[#2a2a40] hover:border-[#b57bee] text-sm font-bold transition-colors"
                >
                  <ChevronLeft size={16} /> Précédent
                </Link>
              ) : (
                <span className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0e0e18] border border-[#2a2a40] text-sm font-bold text-[#3d3d5c] cursor-not-allowed">
                  <ChevronLeft size={16} /> Précédent
                </span>
              )}

              <span className="text-sm text-[#5f5f7a] font-medium px-2">{page} / {totalPages}</span>

              {page < totalPages ? (
                <Link
                  href={buildUrl(page + 1)}
                  className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#b57bee] text-black border border-[#b57bee] text-sm font-bold transition-colors hover:bg-[#c992f5]"
                >
                  Suivant <ChevronRight size={16} />
                </Link>
              ) : (
                <span className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0e0e18] border border-[#2a2a40] text-sm font-bold text-[#3d3d5c] cursor-not-allowed">
                  Suivant <ChevronRight size={16} />
                </span>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
