import prisma from "@/lib/prisma";
import Link from "next/link";
import { photoUrl } from "@/lib/media";
import type { Metadata } from "next";

const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";

export const metadata: Metadata = {
  title: "Marketplace | AdultWorld",
  description:
    "Browse and purchase premium galleries, videos, and exclusive content from verified creators on AdultWorld.",
  alternates: { canonical: `${baseUrl}/marketplace` },
  openGraph: {
    title: "Marketplace | AdultWorld",
    description: "Premium content from verified creators.",
    url: `${baseUrl}/marketplace`,
  },
  twitter: {
    card: "summary_large_image",
    title: "Marketplace | AdultWorld",
    description: "Premium content from verified creators.",
  },
};

export const revalidate = 300;

export default async function MarketplacePage() {
  const [premiumGalleries, premiumVideos] = await Promise.all([
    prisma.gallery.findMany({
      where: { private: false, credits: { gt: 0 }, user: { is: {} } },
      include: {
        user: {
          select: {
            id: true,
            id_aw: true,
            username: true,
            profile_photo: true,
          },
        },
      },
      orderBy: { created_at: "desc" },
      take: 24,
    }),
    prisma.video.findMany({
      where: { private: false, credits: { gt: 0 }, user: { is: {} } },
      include: {
        user: {
          select: {
            id: true,
            id_aw: true,
            username: true,
            profile_photo: true,
          },
        },
      },
      orderBy: { created_at: "desc" },
      take: 24,
    }),
  ]);

  const collectionLd = (premiumGalleries.length + premiumVideos.length) === 0 ? null : {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: "AdultWorld Marketplace",
    url: `${baseUrl}/marketplace`,
    hasPart: [
      {
        "@type": "ItemList",
        name: "Premium Galleries",
        numberOfItems: premiumGalleries.length,
        itemListElement: premiumGalleries.map((g, idx) => ({
          "@type": "ListItem",
          position: idx + 1,
          url: `${baseUrl}/gallery/show/${g.id}`,
          name: g.name,
        })),
      },
      {
        "@type": "ItemList",
        name: "Premium Videos",
        numberOfItems: premiumVideos.length,
        itemListElement: premiumVideos.map((v, idx) => ({
          "@type": "ListItem",
          position: idx + 1,
          name: v.name,
          ...(v.user?.id_aw && { url: `${baseUrl}/view/${v.user.id_aw}` }),
        })),
      },
    ],
  };

  return (
    <div className="max-w-7xl mx-auto py-8 space-y-10">
      {collectionLd && (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(collectionLd) }} />
      )}
      <div className="text-center mb-8">
        <h1 className="text-4xl font-bold text-gold mb-3 font-heading">
          Marketplace
        </h1>
        <p className="text-text-muted text-lg max-w-2xl mx-auto">
          Discover exclusive premium content from verified creators. Use credits
          to unlock galleries and videos.
        </p>
      </div>

      {/* Premium Galleries */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-2xl font-bold font-heading">
            Premium Galleries
          </h2>
          <Link
            href="/galleries"
            className="text-primary text-sm hover:underline"
          >
            View all galleries
          </Link>
        </div>

        {premiumGalleries.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {premiumGalleries.map((gallery) => (
              <Link
                key={gallery.id}
                href={`/gallery/show/${gallery.id}`}
                className="bg-surface rounded-xl overflow-hidden hover:ring-1 hover:ring-primary transition-all group relative"
              >
                <div className="aspect-video bg-surface-light flex items-center justify-center relative">
                  {gallery.cover ? (
                    <img
                      src={photoUrl(gallery.cover, gallery.user?.id_aw)}
                      alt={gallery.name ?? ""}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                    />
                  ) : (
                    <svg
                      className="w-12 h-12 text-text-muted"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={1.5}
                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                      />
                    </svg>
                  )}
                  {/* Price Badge */}
                  <span className="absolute top-2 right-2 bg-primary/90 text-white text-xs font-bold px-2 py-1 rounded-lg backdrop-blur-sm">
                    {gallery.credits} credits
                  </span>
                </div>
                <div className="p-3">
                  <p className="font-semibold truncate">{gallery.name}</p>
                  <p className="text-text-muted text-sm truncate mt-1">
                    {gallery.user?.username}
                  </p>
                </div>
              </Link>
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-text-muted bg-surface rounded-xl">
            <p>No premium galleries available yet.</p>
          </div>
        )}
      </section>

      {/* Premium Videos */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-2xl font-bold font-heading">Premium Videos</h2>
          <Link
            href="/videos"
            className="text-primary text-sm hover:underline"
          >
            View all videos
          </Link>
        </div>

        {premiumVideos.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {premiumVideos.map((video) => (
              <div
                key={video.id}
                className="bg-surface rounded-xl overflow-hidden hover:ring-1 hover:ring-primary transition-all group relative"
              >
                <div className="aspect-video bg-surface-light relative flex items-center justify-center">
                  <svg
                    className="w-12 h-12 text-text-muted"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={1.5}
                      d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"
                    />
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={1.5}
                      d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                  {/* Play overlay */}
                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30">
                    <svg
                      className="w-16 h-16 text-white"
                      fill="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </div>
                  {/* Price Badge */}
                  <span className="absolute top-2 right-2 bg-primary/90 text-white text-xs font-bold px-2 py-1 rounded-lg backdrop-blur-sm">
                    {video.credits} credits
                  </span>
                </div>
                <div className="p-3">
                  <p className="font-semibold truncate">{video.name}</p>
                  <div className="flex items-center justify-between mt-1">
                    <Link
                      href={`/view/${video.user?.id_aw}`}
                      className="text-text-muted text-sm hover:text-primary truncate"
                    >
                      {video.user?.username}
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-text-muted bg-surface rounded-xl">
            <p>No premium videos available yet.</p>
          </div>
        )}
      </section>

      <div className="text-center pt-4">
        <Link
          href="/credits/buy"
          className="inline-block px-8 py-3 rounded-xl gradient-gold text-black font-semibold hover:opacity-90 transition-opacity"
        >
          Buy Credits
        </Link>
      </div>
    </div>
  );
}
