import prisma from "@/lib/prisma";
import Link from "next/link";
import type { Metadata } from "next";
import { auth } from "@/lib/auth";
import StoreClient from "./StoreClient";

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

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

interface StoreItem {
  id: number;
  title: string;
  description: string | null;
  type: string;
  thumbnail: string | null;
  price_credits: number;
  seller_id: number;
  seller_name: string | null;
  seller_photo: string | null;
  created_at: string;
}

export default async function StorePage() {
  const session = await auth();
  let items: StoreItem[] = [];

  try {
    items = await prisma.$queryRawUnsafe<StoreItem[]>(
      `SELECT
        csi.id,
        csi.title,
        csi.description,
        csi.type,
        csi.thumbnail,
        csi.price_credits,
        csi.seller_id,
        u.username AS seller_name,
        u.profile_photo AS seller_photo,
        csi.created_at
      FROM content_store_items csi
      JOIN users u ON u.id = csi.seller_id
      WHERE csi.active = true
      ORDER BY csi.created_at DESC
      LIMIT 60`
    );
  } catch {
    // Table might not exist yet
  }

  const itemListLd = items.length === 0 ? null : {
    "@context": "https://schema.org",
    "@type": "ItemList",
    name: "AdultWorld Premium Content Store",
    numberOfItems: items.length,
    itemListElement: items.map((item, idx) => ({
      "@type": "ListItem",
      position: idx + 1,
      item: {
        "@type": "Product",
        name: item.title,
        ...(item.description && { description: item.description }),
        ...(item.seller_name && {
          seller: { "@type": "Person", name: item.seller_name, url: `${baseUrl}/view/${item.seller_id}` },
        }),
        offers: {
          "@type": "Offer",
          price: item.price_credits,
          priceCurrency: "CREDITS",
          availability: "https://schema.org/InStock",
        },
      },
    })),
  };

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

      {items.length > 0 ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {items.map((item) => (
            <StoreClient
              key={item.id}
              item={item}
              isAuthenticated={!!session?.user}
            />
          ))}
        </div>
      ) : (
        <div className="text-center py-20">
          <svg
            className="w-16 h-16 mx-auto text-text-muted mb-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
            />
          </svg>
          <p className="text-lg text-text-muted">No items in the store yet</p>
          <p className="text-text-muted text-sm mt-1">Check back later for exclusive content</p>
        </div>
      )}

      <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>
  );
}
