export const dynamic = "force-dynamic";

import { Suspense } from "react";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { LayoutGrid, ChevronLeft, ChevronRight } from "lucide-react";
import { HorizontalCarousel } from "@/components/HorizontalCarousel";
import { CreatorCarousel } from "@/components/CreatorCarousel";
import { VideoCard } from "@/components/VideoCard";
import { PersonalizedFeed } from "@/components/PersonalizedFeed";
import { formatNumber } from "@/lib/utils";

const PER_PAGE = 32;

export default async function HomePage({
  searchParams,
}: {
  searchParams: any;
}) {
  let resolvedParams: any = {};
  try {
    resolvedParams = (await searchParams) || {};
  } catch {
    resolvedParams = {};
  }

  const pageParam = resolvedParams.page;
  const cat = resolvedParams.cat;
  const tab = resolvedParams.tab || "foryou";
  const page = Math.max(1, parseInt(pageParam || "1") || 1);

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

  let trendingVideos: any[] = [];
  let allCategories: any[] = [];
  let videos: any[] = [];
  let latestVideos: any[] = [];
  let topCreatorsData: any[] = [];

  try {
    const [tV, aC, vD, lV, tC] = await Promise.all([
      page === 1
        ? prisma.media.findMany({
            where: { type: "VIDEO", isPublished: true },
            orderBy: { createdAt: "desc" },
            take: 5,
            select: {
              id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
              uploader: { select: { id: true, name: true, image: true } }
            }
          }).catch(() => [])
        : Promise.resolve([]),
      prisma.category.findMany({
        take: 40,
        select: { id: true, name: true, slug: true },
      }).catch(() => []),
      !showForYou
        ? prisma.media.findMany({
            where,
            orderBy: { createdAt: "desc" },
            skip: (page - 1) * PER_PAGE,
            take: PER_PAGE,
            select: {
              id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
              uploader: { select: { id: true, name: true, image: true } },
              category: { select: { name: true, slug: true } }
            }
          }).catch(() => [])
        : Promise.resolve([]),
      page === 1 && showForYou
        ? prisma.media.findMany({
            where: { type: "VIDEO", isPublished: true },
            orderBy: { views: "desc" },
            take: 8,
            select: {
              id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
              uploader: { select: { id: true, name: true, image: true } },
              category: { select: { name: true, slug: true } }
            }
          }).catch(() => [])
        : Promise.resolve([]),
      page === 1 && showForYou
        ? (async () => {
            try {
              const topToday = await prisma.media.findMany({
                where: { type: "VIDEO", isPublished: true, uploaderId: { not: null } },
                orderBy: { views: "desc" },
                take: 40,
                select: { uploader: { select: { id: true, name: true, image: true } } }
              });
              const map = new Map();
              (topToday || []).forEach(m => {
                if (m?.uploader && !map.has(m.uploader.id)) {
                  map.set(m.uploader.id, m.uploader);
                }
              });
              return Array.from(map.values()).slice(0, 10);
            } catch {
              return [];
            }
          })()
        : Promise.resolve([]),
    ]);

    trendingVideos = tV || [];
    allCategories = aC || [];
    videos = vD || [];
    latestVideos = lV || [];
    topCreatorsData = tC || [];
  } catch (e) {
    console.error("Error fetching homepage data:", e);
  }

  // Fetch Continue Watching if ForYou and user is logged in
  let continueWatching: any[] = [];
  if (showForYou && page === 1) {
    try {
      const session = await import("@/lib/auth").then(m => m.auth()).catch(() => null);
      const userId = (session?.user as any)?.id;
      if (userId) {
        const history = await prisma.watchHistory.findMany({
          where: { userId },
          orderBy: { updatedAt: "desc" },
          take: 4,
          select: {
            media: {
              select: {
                id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true, isPublished: true, type: true,
                category: { select: { id: true, name: true, slug: true } }
              }
            }
          }
        }).catch(() => []);
        continueWatching = (history || []).map(h => h.media).filter(m => m && m.isPublished && m.type === "VIDEO");
      }
    } catch (e) {
      console.error("Error loading continue watching:", e);
    }
  }

  const total = 10000;
  const topCreators = (topCreatorsData || []).map((user: any, index: number) => ({
    id: user?.id || String(index),
    name: user?.name || "Anonyme",
    image: user?.image || "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=400&q=80",
    isOnline: index % 2 === 0,
    rank: index + 1,
  }));

  const totalPages = Math.ceil(total / PER_PAGE);
  const isCleanName = (name: string) => Boolean(name && typeof name === "string" && !/^[\d°\s.\-/°]+$/.test(name) && name.length > 2);
  const topCategories = (allCategories || []).filter((c) => 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="w-full pb-8 min-h-screen relative">
      <div className="absolute top-0 inset-x-0 h-[500px] bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-[#b57bee]/15 via-[#050508]/0 to-transparent pointer-events-none -z-10" />

      <div className="max-w-[2000px] mx-auto pt-6 lg:pt-10">
        
        {/* Categories Bar */}
        <div className="flex gap-3 overflow-x-auto pb-6 px-4 lg:px-8 scrollbar-hide relative z-10 mask-linear-fade">
          <Link
            href="/?tab=all"
            className={`flex-shrink-0 flex items-center gap-2 px-5 py-2.5 rounded-2xl text-sm font-bold transition-all duration-300 ${
              tab === "all" && !cat
                ? "bg-gradient-to-r from-[#b57bee] to-[#c992f5] text-black shadow-[0_0_30px_rgba(181,123,238,0.3)] scale-105"
                : "bg-[#11111a]/80 backdrop-blur-md border border-[#222233] text-[#9d9db8] hover:border-[#b57bee]/50 hover:text-white hover:bg-[#181824]"
            }`}
          >
            Toutes les vidéos
          </Link>
          <div className="w-px h-8 bg-gradient-to-b from-transparent via-[#2a2a40] to-transparent mx-2 self-center flex-shrink-0" />
          {topCategories.map((c) => (
            <Link
              key={c.id || c.slug || c.name}
              href={`/?cat=${c.id}`}
              className={`flex-shrink-0 px-5 py-2.5 rounded-2xl text-sm font-semibold transition-all duration-300 ${
                cat === c.id
                  ? "bg-gradient-to-r from-[#b57bee] to-[#c992f5] text-black shadow-[0_0_30px_rgba(181,123,238,0.3)] scale-105"
                  : "bg-[#11111a]/80 backdrop-blur-md border border-[#222233] text-[#9d9db8] hover:border-[#b57bee]/50 hover:text-white hover:bg-[#181824]"
              }`}
            >
              {c.name}
            </Link>
          ))}
          <Link
            href="/categories"
            className="flex-shrink-0 flex items-center gap-2 px-5 py-2.5 rounded-2xl text-sm font-bold bg-[#11111a]/80 backdrop-blur-md border border-[#b57bee]/30 text-[#b57bee] hover:bg-[#b57bee]/10 hover:border-[#b57bee] transition-all duration-300"
          >
            <LayoutGrid size={16} /> Tout voir
          </Link>
        </div>

        {showForYou ? (
          <>
            {continueWatching.length > 0 && (
              <Suspense fallback={null}>
                <HorizontalCarousel title="Reprendre la lecture" videos={continueWatching} />
              </Suspense>
            )}

            {latestVideos.length > 0 && (
              <Suspense fallback={null}>
                <HorizontalCarousel title="Tendances 🔥" videos={latestVideos} viewAllLink="/?tab=all" />
              </Suspense>
            )}

            {topCreators.length > 0 && (
              <Suspense fallback={null}>
                <CreatorCarousel title="Modèles de la semaine" creators={topCreators} />
              </Suspense>
            )}
            
            <div className="px-4 lg:px-8">
              <Suspense fallback={<div className="h-96 animate-pulse bg-[#11111a] rounded-2xl" />}>
                <PersonalizedFeed />
              </Suspense>
            </div>
          </>
        ) : (
          <div className="px-4 lg:px-8">
            <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>

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

            {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>
        )}
      </div>
    </div>
  );
}
