import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { Crown, Eye, Heart, Lock, Search, SlidersHorizontal, Image } from "lucide-react";
import { formatNumber, timeAgo } from "@/lib/utils";

export const metadata = { title: "Galerie Photos" };

export default async function PhotosPage({ searchParams }: { searchParams: Promise<{ q?: string; cat?: string; access?: string }> }) {
  const session = await auth();
  const isPremium = (session?.user as any)?.isPremium;
  const params = await searchParams;
  const { q, cat, access } = params;

  const where: any = { type: "PHOTO", 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;

  const [photos, categories] = await Promise.all([
    prisma.media.findMany({
      where, orderBy: { createdAt: "desc" }, take: 60,
      include: { category: true, _count: { select: { likes: true } } },
    }),
    prisma.category.findMany({ orderBy: { order: "asc" } }),
  ]);

  return (
    <div className="min-h-screen py-8 px-4">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-black mb-2">
            <Image size={28} className="inline mr-2" style={{ color: "#e05a68" }} />
            Galerie <span className="gradient-text">Photos</span>
          </h1>
          <p style={{ color: "var(--text-secondary)" }}>{photos.length} photos disponibles</p>
        </div>

        {/* Filters */}
        <form className="flex flex-wrap gap-3 mb-8">
          <div className="relative flex-1 min-w-[200px]">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-muted)" }} />
            <input name="q" defaultValue={q} type="text" placeholder="Rechercher..." className="input pl-9 text-sm" />
          </div>
          <select name="cat" defaultValue={cat} className="input text-sm w-auto">
            <option value="">Toutes catégories</option>
            {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <select name="access" defaultValue={access} className="input text-sm w-auto">
            <option value="">Tout accès</option>
            <option value="free">Gratuit</option>
            <option value="premium">VIP</option>
          </select>
          <button type="submit" className="btn btn-primary text-sm px-4">
            <SlidersHorizontal size={14} /> Filtrer
          </button>
        </form>

        {photos.length === 0 ? (
          <div className="text-center py-20" style={{ color: "var(--text-muted)" }}>
            <Image size={48} className="mx-auto mb-4 opacity-30" />
            <p>Aucune photo trouvée.</p>
          </div>
        ) : (
          <div className="columns-2 md:columns-3 lg:columns-4 gap-4">
            {photos.map(media => {
              const isLocked = media.isPremium && !isPremium;
              return (
                <div key={media.id} className="break-inside-avoid mb-4">
                  <Link href={isLocked ? "/premium" : `/photo/${media.id}`} className="block group relative overflow-hidden rounded-xl" style={{ textDecoration: "none" }}>
                    {media.thumbnailUrl || media.url ? (
                      <img
                        src={media.thumbnailUrl || media.url}
                        alt={media.title}
                        className="w-full transition-transform duration-500 group-hover:scale-105"
                        loading="lazy"
                        style={{ filter: isLocked ? "blur(8px)" : "none", display: "block" }}
                      />
                    ) : (
                      <div className="w-full h-40 flex items-center justify-center" style={{ background: "var(--bg-card)" }}>
                        <Image size={32} style={{ color: "var(--text-muted)" }} />
                      </div>
                    )}

                    {/* Lock overlay */}
                    {isLocked && (
                      <div className="absolute inset-0 flex flex-col items-center justify-center" style={{ background: "rgba(10,10,15,0.6)", backdropFilter: "blur(2px)" }}>
                        <Lock size={24} style={{ color: "#fbbf24" }} />
                        <span className="text-xs font-bold mt-1" style={{ color: "#fbbf24" }}>VIP</span>
                      </div>
                    )}

                    {/* Hover overlay */}
                    <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col justify-end p-3" style={{ background: "linear-gradient(to top, rgba(0,0,0,0.8), transparent)" }}>
                      <div className="flex items-start justify-between">
                        <p className="text-sm font-semibold text-white line-clamp-1">{media.title}</p>
                        <span className={`badge ${media.isPremium ? "badge-premium" : "badge-free"} ml-2 flex-shrink-0`}>
                          {media.isPremium ? <Crown size={9} /> : null} {media.isPremium ? "VIP" : "Free"}
                        </span>
                      </div>
                      <div className="flex items-center gap-3 mt-1 text-xs" style={{ color: "rgba(255,255,255,0.7)" }}>
                        <span className="flex items-center gap-1"><Eye size={11} /> {formatNumber(media.views)}</span>
                        <span className="flex items-center gap-1"><Heart size={11} /> {formatNumber(media._count.likes)}</span>
                      </div>
                    </div>
                  </Link>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
