import { connectMongo } from "@/lib/mongo";
import { Product } from "@/models/Product";
import { Category } from "@/models/Category";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function ProductDetailPage({
  params,
}: {
  params: { slug: string };
}) {
  await connectMongo();
  const product = await Product.findOne({ slug: params.slug }).lean();
  if (!product) notFound();

  const category = await Category.findById(product.categoryId).lean();

  const url = `/api/files/${String(product.mediaFileId)}`;

  return (
    <div className="max-w-5xl mx-auto px-6 lg:px-10 pt-10 lg:pt-16 pb-16">
      <Link
        href="/portfolio"
        className="inline-flex items-center gap-2 text-sm text-brand-300 hover:text-white transition mb-6"
      >
        <ArrowLeft className="w-4 h-4" />
        Portfolyoya dön
      </Link>

      <div className="glass-strong rounded-2xl overflow-hidden">
        <div className="bg-black/40 flex items-center justify-center max-h-[70vh]">
          {product.mediaType === "video" ? (
            <video
              src={url}
              controls
              autoPlay
              loop
              className="max-h-[70vh] w-auto"
            />
          ) : (
            <img
              src={url}
              alt={product.title}
              className="max-h-[70vh] w-auto object-contain"
            />
          )}
        </div>

        <div className="p-6 lg:p-8">
          {category && (
            <span className="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-brand-700/40 text-brand-100 border border-brand-600/40 mb-3">
              {category.name}
            </span>
          )}
          <h1 className="text-2xl lg:text-3xl font-bold text-white">
            {product.title}
          </h1>
          {product.description && (
            <p className="mt-4 text-brand-200 leading-relaxed whitespace-pre-line">
              {product.description}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
