// app/products/[slug]/page.tsx
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import ProductGallery from "@/components/ProductGallery";
import ProductCard from "@/components/ProductCard";
import DetailActionButtons from "@/components/DetailActionButtons";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import {
  Layers,
  Sparkles,
  FileCheck2,
  Palette,
  HardDrive,
  ArrowLeft,
  Edit3,
} from "lucide-react";
import Link from "next/link";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export const dynamic = "force-dynamic";

export default async function ProductDetailPage(props: PageProps) {
  // 1. Unwrapping params Promise (Next.js 15+ requirement)
  const { slug } = await props.params;

  if (!slug) {
    notFound();
  }

  // 2. Fetch current user session to check for ADMIN role
  const session = await getServerSession(authOptions);
  const isAdmin = (session?.user as any)?.role === "ADMIN";

  // 3. Fetch current product from MySQL
  const product = await prisma.product.findUnique({
    where: { slug: slug },
  });

  if (!product) {
    notFound();
  }

  // Parse multi-angle preview images
  let images: string[] = [product.thumbnailUrl];
  if (product.previewUrls) {
    try {
      const parsed = JSON.parse(product.previewUrls);
      if (Array.isArray(parsed) && parsed.length > 0) {
        images = parsed;
      }
    } catch {
      images = [product.thumbnailUrl];
    }
  }

  // 4. Fetch related products from the same category
  const relatedProducts = await prisma.product.findMany({
    where: {
      category: product.category,
      id: { not: product.id },
    },
    take: 4,
    orderBy: { createdAt: "desc" },
  });

  const priceNum = Number(product.price);
  const discountNum = product.discountPrice ? Number(product.discountPrice) : null;

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 py-10 px-4 sm:px-6 max-w-7xl mx-auto space-y-16">
      {/* Top Header & Breadcrumbs */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-xs text-zinc-400">
          <Link href="/" className="hover:text-white flex items-center gap-1 transition">
            <ArrowLeft className="h-3.5 w-3.5" /> Back to Store
          </Link>
          <span>/</span>
          <span className="text-zinc-500">{product.category}</span>
          <span>/</span>
          <span className="text-indigo-400 font-medium truncate max-w-xs">{product.title}</span>
        </div>

        {/* Admin Edit Button (Visible ONLY to Logged-in Admins) */}
        {isAdmin && (
          <Link
            href={`/admin/edit/${product.id}`}
            className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-indigo-500/10 border border-indigo-500/30 text-indigo-400 text-xs font-semibold hover:bg-indigo-500/20 transition shadow-sm"
          >
            <Edit3 className="h-3.5 w-3.5" /> Edit Template (Admin)
          </Link>
        )}
      </div>

      {/* Main Showcase Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
        {/* Left 7 Columns: Multi-Angle Interactive Gallery */}
        <div className="lg:col-span-7">
          <ProductGallery images={images} title={product.title} fileType={product.fileType} />
        </div>

        {/* Right 5 Columns: Product Information & Purchase Card */}
        <div className="lg:col-span-5 space-y-6">
          <div>
            <div className="flex items-center gap-2 mb-3">
              <span className="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-indigo-500/10 border border-indigo-500/20 text-indigo-400">
                {product.category}
              </span>
              <span className="inline-block px-2.5 py-0.5 rounded-md text-[11px] font-bold bg-zinc-900 border border-zinc-800 text-zinc-300">
                .{product.fileType}
              </span>
            </div>

            <h1 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight leading-snug">
              {product.title}
            </h1>
            <p className="text-zinc-400 text-xs mt-2 flex items-center gap-2">
              <span>{product.downloads} downloads</span>
              <span>•</span>
              <span className="text-emerald-400 font-medium">Instant ZIP Delivery</span>
            </p>
          </div>

          {/* Pricing Box */}
          <div className="p-5 rounded-2xl bg-zinc-900/70 border border-zinc-800 space-y-4">
            <div className="flex items-baseline gap-3">
              <span className="text-3xl font-black text-white">₹{priceNum.toFixed(2)}</span>
              {discountNum && (
                <span className="text-base text-zinc-500 line-through">₹{discountNum.toFixed(2)}</span>
              )}
              {discountNum && (
                <span className="text-xs font-bold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded">
                  Save {Math.round(((discountNum - priceNum) / discountNum) * 100)}%
                </span>
              )}
            </div>

            {/* Action Buttons */}
            <DetailActionButtons
              id={product.id}
              title={product.title}
              price={priceNum}
              fileType={product.fileType}
              thumbnailUrl={product.thumbnailUrl}
            />
          </div>

          {/* Design & Print Specifications */}
          <div className="space-y-3 pt-2">
            <h3 className="text-sm font-bold uppercase tracking-wider text-zinc-400">
              Technical Specifications
            </h3>

            <div className="grid grid-cols-2 gap-3 text-xs">
              <div className="p-3 rounded-xl bg-zinc-900/40 border border-zinc-800 flex items-center gap-3">
                <FileCheck2 className="h-5 w-5 text-indigo-400 flex-shrink-0" />
                <div>
                  <span className="text-zinc-500 block">Primary Format</span>
                  <span className="font-semibold text-white">.{product.fileType} + Auto ZIP</span>
                </div>
              </div>

              <div className="p-3 rounded-xl bg-zinc-900/40 border border-zinc-800 flex items-center gap-3">
                <Palette className="h-5 w-5 text-indigo-400 flex-shrink-0" />
                <div>
                  <span className="text-zinc-500 block">Color Mode</span>
                  <span className="font-semibold text-white">CMYK (300 DPI)</span>
                </div>
              </div>

              <div className="p-3 rounded-xl bg-zinc-900/40 border border-zinc-800 flex items-center gap-3">
                <HardDrive className="h-5 w-5 text-indigo-400 flex-shrink-0" />
                <div>
                  <span className="text-zinc-500 block">File Size</span>
                  <span className="font-semibold text-white">{product.fileSize}</span>
                </div>
              </div>

              <div className="p-3 rounded-xl bg-zinc-900/40 border border-zinc-800 flex items-center gap-3">
                <Layers className="h-5 w-5 text-indigo-400 flex-shrink-0" />
                <div>
                  <span className="text-zinc-500 block">Editing Software</span>
                  <span className="font-semibold text-white">
                    {product.fileType === "CDR" ? "CorelDRAW X7-2026" : "Photoshop CC"}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Description */}
          {product.description && (
            <div className="space-y-2 pt-2 border-t border-zinc-900">
              <h4 className="text-xs font-bold text-zinc-400 uppercase tracking-wider">
                Font & Template Description
              </h4>
              <p className="text-xs text-zinc-300 leading-relaxed whitespace-pre-line bg-zinc-900/30 p-4 rounded-xl border border-zinc-800/60">
                {product.description}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Same Category Recommendations */}
      <section className="space-y-6 pt-10 border-t border-zinc-900">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl sm:text-2xl font-bold text-white tracking-tight">
              More Designs in <span className="text-indigo-400">{product.category}</span>
            </h2>
            <p className="text-xs text-zinc-400 mt-1">Explore similar templates ready for instant download.</p>
          </div>
          <Link
            href={`/?category=${encodeURIComponent(product.category)}`}
            className="text-xs font-semibold text-indigo-400 hover:text-indigo-300 transition"
          >
            View All →
          </Link>
        </div>

        {relatedProducts.length === 0 ? (
          <p className="text-xs text-zinc-500 py-6">No other designs in this category yet.</p>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {relatedProducts.map((item) => (
              <ProductCard
                key={item.id}
                id={item.id}
                title={item.title}
                slug={item.slug}
                category={item.category}
                fileType={item.fileType}
                price={Number(item.price)}
                discountPrice={item.discountPrice ? Number(item.discountPrice) : null}
                thumbnailUrl={item.thumbnailUrl}
                fileSize={item.fileSize}
              />
            ))}
          </div>
        )}
      </section>
    </div>
  );
}