import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import Link from "next/link";
import { Play, SlidersHorizontal, Flame, Sparkles, Filter, ChevronLeft, ChevronRight, Eye } from "lucide-react";
import { MediaCard } from "@/components/MediaCard";
import { AdVideoCard } from "@/components/AdVideoCard";
import { expandSearchQuery } from "@/lib/searchTranslation";
import { SearchTracker } from "@/components/SearchTracker";
import { getCached, setCached } from "@/lib/memoryCache";

export const dynamic = "force-dynamic";

const PER_PAGE = 36;

export async function generateMetadata({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const { q } = await searchParams;
  return {
    title: q ? `Vidéos "${q}" HD Gratuites | MTBR` : "Toutes les Vidéos HD | MTBR",
    description: q
      ? `Regardez les meilleures vidéos ${q} en streaming HD gratuit sur MTBR. Nouveautés quotidiennes, 4K/HD sans inscription.`
      : "Parcourez notre catalogue complet de plus de 10 000 vidéos gratuites en HD et 4K sur MTBR (Made To Break Rules).",
  };
}

export default async function VideosPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; cat?: string; sort?: string; access?: string; duration?: string; page?: string }>;
}) {
  const session = await auth();
  const params = await searchParams;
  const { q, cat, sort = "views", access, duration, page: pageParam } = params as any;
  const page = Math.max(1, parseInt(pageParam || "1"));

  const where: any = {
    type: "VIDEO",
    isPublished: true,
  };
  if (q) {
    where.title = { contains: q };
  }

  if (cat) where.categoryId = cat;
  if (access === "free") where.isPremium = false;
  if (access === "premium") where.isPremium = true;
  if (duration === "short") where.duration = { lt: 300 };
  else if (duration === "medium") where.duration = { gte: 300, lt: 1200 };
  else if (duration === "long") where.duration = { gte: 1200 };

  // ⚡ Utilise impérativement les index composites haute performance
  const orderBy: any = sort === "recent" || sort === "latest"
    ? { createdAt: "desc" }
    : { views: "desc" };

  const cacheKey = `videos_${q || "all"}_${cat || "all"}_${sort}_${access || "all"}_${duration || "all"}_${page}`;
  const cached = getCached<{ videos: any[]; categories: any[] }>(cacheKey);

  let videos: any[] = [];
  let categories: any[] = [];

  if (cached) {
    videos = cached.videos;
    categories = cached.categories;
  } else {
    [videos, categories] = await Promise.all([
      prisma.media.findMany({
        where: Object.keys(where).length > 0 ? where : undefined,
        orderBy,
        skip: (page - 1) * PER_PAGE,
        take: PER_PAGE,
        select: {
          id: true,
          title: true,
          titleFr: true,
          thumbnailUrl: true,
          duration: true,
          views: true,
          isPremium: true,
          
          createdAt: true,
          category: { select: { id: true, name: true, slug: true } },
          uploader: { select: { id: true, name: true, image: true, isVerified: true } },
        },
      }),
      prisma.category.findMany({ take: 30, select: { id: true, name: true, slug: true } }),
    ]);

    setCached(cacheKey, { videos, categories }, 30000); // 30s cache
  }

  const total = 10000;
  const totalPages = Math.ceil(total / PER_PAGE);

  const buildUrl = (p: number) => {
    const sp = new URLSearchParams();
    if (q) sp.set("q", q);
    if (cat) sp.set("cat", cat);
    if (sort) sp.set("sort", sort);
    if (access) sp.set("access", access);
    if (duration) sp.set("duration", duration);
    sp.set("page", String(p));
    return `/videos?${sp.toString()}`;
  };

  const popularTags = [
    { label: "Français", query: "francais", icon: "🇫🇷" },
    { label: "Amateur", query: "amateur", icon: "🔥" },
    { label: "Hentai", query: "hentai", icon: "⚡" },
    { label: "Beurette", query: "beurette", icon: "🌶️" },
    { label: "MILF", query: "milf", icon: "👑" },
    { label: "Anal", query: "anal", icon: "💥" },
    { label: "Lesbienne", query: "lesbienne", icon: "❤️" },
    { label: "4K HD", query: "4k", icon: "✨" },
    { label: "Exclusif", query: "exclusif", icon: "🎬" },
    { label: "VR", query: "vr", icon: "🥽" },
  ];

  return (
    <div className="min-h-screen bg-[#070406] text-white py-6 px-3 md:px-6">
      <div className="max-w-[1800px] mx-auto">
        <SearchTracker />

        {/* 🚀 BANNIÈRE HERO DE LA PAGE VIDÉOS */}
        <div className="relative mb-8 rounded-3xl overflow-hidden bg-gradient-to-r from-[#2e0e14] via-[#15070a] to-[#070406] border border-[#2e1217] p-6 md:p-8 shadow-2xl">
          <div className="absolute -right-20 -bottom-20 w-96 h-96 bg-[#e05a68]/15 rounded-full blur-3xl pointer-events-none" />
          
          <div className="relative z-10 max-w-3xl">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#e05a68]/20 border border-[#e05a68]/40 text-[#e05a68] text-xs font-black uppercase tracking-wider mb-3">
              <Sparkles size={14} /> CATALOGUE OFFICIEL MTBR
            </div>
            
            <h1 className="text-2xl md:text-4xl font-black text-white leading-tight mb-3">
              {q ? (
                <>Résultats pour <span className="text-[#e05a68]">"{q}"</span></>
              ) : (
                <>Toutes les <span className="bg-gradient-to-r from-[#c93f52] to-[#e05a68] bg-clip-text text-transparent">Vidéos Exclusives</span> en Streaming HD</>
              )}
            </h1>

            <p className="text-[#d8cbd0] text-xs md:text-sm font-medium leading-relaxed mb-4">
              Explorez des milliers de vidéos haute définition. Streaming instantané, créateurs certifiés MTBR et contenus exclusifs mis à jour 24h/24.
            </p>

            <div className="flex flex-wrap items-center gap-4 text-xs font-bold text-[#8c7e84]">
              <span className="flex items-center gap-1.5 text-white">
                <Flame size={16} className="text-[#e05a68]" /> <strong className="text-[#e05a68]">10 000+</strong> Vidéos
              </span>
              <span>•</span>
              <span className="flex items-center gap-1.5 text-white">
                <Eye size={16} className="text-emerald-400" /> <strong className="text-emerald-400">100% Gratuit</strong>
              </span>
              <span>•</span>
              <span>Qualité 1080p & 4K</span>
            </div>
          </div>
        </div>

        {/* 🏷️ BARRE DE TAGS & FILTRES RAPIDES */}
        <div className="mb-8">
          <div className="flex items-center justify-between gap-3 mb-3">
            <h2 className="text-sm font-black text-white uppercase tracking-wider flex items-center gap-2">
              <Filter size={16} className="text-[#e05a68]" /> Mots-clés populaires
            </h2>
            <span className="text-xs text-[#8c7e84] font-bold">Filtre rapide</span>
          </div>

          <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide pb-2">
            <Link
              href="/videos"
              prefetch={true}
              className={`flex-shrink-0 px-4 py-2 rounded-full text-xs font-extrabold transition-all border ${
                !q
                  ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] border-[#e05a68] text-white shadow-[0_0_15px_rgba(224,90,104,0.4)]"
                  : "bg-[#12080b] border-[#2e1217] text-[#d8cbd0] hover:border-[#e05a68] hover:text-white"
              }`}
            >
              🔥 Tout voir
            </Link>

            {popularTags.map((t) => (
              <Link
                key={t.query}
                href={`/videos?q=${t.query}`}
                prefetch={true}
                className={`flex-shrink-0 flex items-center gap-1.5 px-4 py-2 rounded-full text-xs font-extrabold transition-all border ${
                  q?.toLowerCase() === t.query
                    ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] border-[#e05a68] text-white shadow-[0_0_15px_rgba(224,90,104,0.4)]"
                    : "bg-[#12080b] border-[#2e1217] text-[#d8cbd0] hover:border-[#e05a68] hover:text-white"
                }`}
              >
                <span>{t.icon}</span>
                <span>{t.label}</span>
              </Link>
            ))}
          </div>
        </div>

        {/* 🎥 GRILLE DES VIDÉOS */}
        {videos.length === 0 ? (
          <div className="text-center py-24 bg-[#12080b] rounded-3xl border border-[#2e1217]">
            <Play size={56} className="mx-auto mb-4 text-[#8c7e84] opacity-30" />
            <p className="text-xl font-black text-white mb-2">Aucune vidéo trouvée</p>
            <p className="text-sm text-[#8c7e84] mb-6">Essayez une autre recherche ou réinitialisez les filtres.</p>
            <Link
              href="/videos"
              className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white font-bold text-sm hover:opacity-95 shadow-[0_0_20px_rgba(224,90,104,0.35)] transition-all"
            >
              Voir toutes les vidéos
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 2xl:grid-cols-6 gap-4 md:gap-6 mb-12">
            {videos.map((media, index) => (
              <div key={media.id} className="contents">
                {index === 2 && <AdVideoCard key="ad-native-videos" />}
                <MediaCard media={media} showUploader={true} />
              </div>
            ))}
          </div>
        )}

        {/* 🔢 PAGINATION AMÉLIORÉE */}
        {totalPages > 1 && (
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-8 border-t border-[#2e1217] mb-12">
            <p className="text-xs font-bold text-[#8c7e84]">
              Affichage de la page <span className="text-white font-black">{page}</span> sur <span className="text-white font-black">{totalPages}</span>
            </p>

            <div className="flex items-center gap-2">
              {page > 1 ? (
                <Link
                  href={buildUrl(page - 1)}
                  className="flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-[#12080b] border border-[#2e1217] text-xs font-extrabold text-white hover:border-[#e05a68] transition-all"
                >
                  <ChevronLeft size={16} /> Précédent
                </Link>
              ) : (
                <span className="flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-[#0a0507] border border-[#1f0d11] text-xs font-extrabold text-[#5c3038] cursor-not-allowed">
                  <ChevronLeft size={16} /> Précédent
                </span>
              )}

              <span className="px-4 py-2 rounded-full bg-[#e05a68]/20 border border-[#e05a68] text-white text-xs font-black">
                {page}
              </span>

              {page < totalPages ? (
                <Link
                  href={buildUrl(page + 1)}
                  className="flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white text-xs font-extrabold hover:opacity-95 transition-all shadow-[0_0_15px_rgba(224,90,104,0.4)]"
                >
                  Suivant <ChevronRight size={16} />
                </Link>
              ) : (
                <span className="flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-[#0a0507] border border-[#1f0d11] text-xs font-extrabold text-[#5c3038] cursor-not-allowed">
                  Suivant <ChevronRight size={16} />
                </span>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
